Best Python code snippet using autotest_python
parttool.py
Source:parttool.py  
...120                    break121        if not partition:122            raise Exception('Partition does not exist')123        return partition124    def erase_partition(self, partition_id):125        partition = self.get_partition_info(partition_id)126        self._call_esptool(['erase_region', str(partition.offset),  str(partition.size)] + self.esptool_erase_args)127    def read_partition(self, partition_id, output):128        partition = self.get_partition_info(partition_id)129        self._call_esptool(['read_flash', str(partition.offset), str(partition.size), output] + self.esptool_read_args)130    def write_partition(self, partition_id, input):131        self.erase_partition(partition_id)132        partition = self.get_partition_info(partition_id)133        with open(input, 'rb') as input_file:134            content_len = len(input_file.read())135            if content_len > partition.size:136                raise Exception('Input file size exceeds partition size')137        self._call_esptool(['write_flash', str(partition.offset), input] + self.esptool_write_args)138def _write_partition(target, partition_id, input):139    target.write_partition(partition_id, input)140    partition = target.get_partition_info(partition_id)141    status("Written contents of file '{}' at offset 0x{:x}".format(input, partition.offset))142def _read_partition(target, partition_id, output):143    target.read_partition(partition_id, output)144    partition = target.get_partition_info(partition_id)145    status("Read partition '{}' contents from device at offset 0x{:x} to file '{}'"146           .format(partition.name, partition.offset, output))147def _erase_partition(target, partition_id):148    target.erase_partition(partition_id)149    partition = target.get_partition_info(partition_id)150    status("Erased partition '{}' at offset 0x{:x}".format(partition.name, partition.offset))151def _get_partition_info(target, partition_id, info):152    try:153        partitions = target.get_partition_info(partition_id)154        if not isinstance(partitions, list):155            partitions = [partitions]156    except Exception:157        return158    infos = []159    try:160        for p in partitions:161            info_dict = {162                'name': '{}'.format(p.name),...common.py
Source:common.py  
1"""Common methods used across tests for TotalConnect."""2from unittest.mock import patch3from total_connect_client import ArmingState, ResultCode, ZoneStatus, ZoneType4from homeassistant.components.totalconnect.const import CONF_USERCODES, DOMAIN5from homeassistant.const import CONF_PASSWORD, CONF_USERNAME6from homeassistant.setup import async_setup_component7from tests.common import MockConfigEntry8LOCATION_ID = "123456"9DEVICE_INFO_BASIC_1 = {10    "DeviceID": "987654",11    "DeviceName": "test",12    "DeviceClassID": 1,13    "DeviceSerialNumber": "987654321ABC",14    "DeviceFlags": "PromptForUserCode=0,PromptForInstallerCode=0,PromptForImportSecuritySettings=0,AllowUserSlotEditing=0,CalCapable=1,CanBeSentToPanel=0,CanArmNightStay=0,CanSupportMultiPartition=0,PartitionCount=0,MaxPartitionCount=0,OnBoardingSupport=0,PartitionAdded=0,DuplicateUserSyncStatus=0,PanelType=8,PanelVariant=1,BLEDisarmCapable=0,ArmHomeSupported=0,DuplicateUserCodeCheck=1,CanSupportRapid=0,IsKeypadSupported=1,WifiEnrollmentSupported=0,IsConnectedPanel=0,ArmNightInSceneSupported=0,BuiltInCameraSettingsSupported=0,ZWaveThermostatScheduleDisabled=0,MultipleAuthorityLevelSupported=0,VideoOnPanelSupported=0,EnableBLEMode=0,IsPanelWiFiResetSupported=0,IsCompetitorClearBypass=0,IsNotReadyStateSupported=0,isArmStatusWithoutExitDelayNotSupported=0",15    "SecurityPanelTypeID": None,16    "DeviceSerialText": None,17}18DEVICE_LIST = [DEVICE_INFO_BASIC_1]19LOCATION_INFO_BASIC_NORMAL = {20    "LocationID": LOCATION_ID,21    "LocationName": "test",22    "SecurityDeviceID": "987654",23    "PhotoURL": "http://www.example.com/some/path/to/file.jpg",24    "LocationModuleFlags": "Security=1,Video=0,Automation=0,GPS=0,VideoPIR=0",25    "DeviceList": {"DeviceInfoBasic": DEVICE_LIST},26}27LOCATIONS = {"LocationInfoBasic": [LOCATION_INFO_BASIC_NORMAL]}28MODULE_FLAGS = "Some=0,Fake=1,Flags=2"29USER = {30    "UserID": "1234567",31    "Username": "username",32    "UserFeatureList": "Master=0,User Administration=0,Configuration Administration=0",33}34RESPONSE_AUTHENTICATE = {35    "ResultCode": ResultCode.SUCCESS.value,36    "SessionID": 1,37    "Locations": LOCATIONS,38    "ModuleFlags": MODULE_FLAGS,39    "UserInfo": USER,40}41RESPONSE_AUTHENTICATE_FAILED = {42    "ResultCode": ResultCode.BAD_USER_OR_PASSWORD.value,43    "ResultData": "test bad authentication",44}45PARTITION_DISARMED = {46    "PartitionID": "1",47    "ArmingState": ArmingState.DISARMED,48}49PARTITION_DISARMED2 = {50    "PartitionID": "2",51    "ArmingState": ArmingState.DISARMED,52}53PARTITION_ARMED_STAY = {54    "PartitionID": "1",55    "ArmingState": ArmingState.ARMED_STAY,56}57PARTITION_ARMED_STAY2 = {58    "PartitionID": "2",59    "ArmingState": ArmingState.DISARMED,60}61PARTITION_ARMED_AWAY = {62    "PartitionID": "1",63    "ArmingState": ArmingState.ARMED_AWAY,64}65PARTITION_ARMED_CUSTOM = {66    "PartitionID": "1",67    "ArmingState": ArmingState.ARMED_CUSTOM_BYPASS,68}69PARTITION_ARMED_NIGHT = {70    "PartitionID": "1",71    "ArmingState": ArmingState.ARMED_STAY_NIGHT,72}73PARTITION_ARMING = {74    "PartitionID": "1",75    "ArmingState": ArmingState.ARMING,76}77PARTITION_DISARMING = {78    "PartitionID": "1",79    "ArmingState": ArmingState.DISARMING,80}81PARTITION_TRIGGERED_POLICE = {82    "PartitionID": "1",83    "ArmingState": ArmingState.ALARMING,84}85PARTITION_TRIGGERED_FIRE = {86    "PartitionID": "1",87    "ArmingState": ArmingState.ALARMING_FIRE_SMOKE,88}89PARTITION_TRIGGERED_CARBON_MONOXIDE = {90    "PartitionID": "1",91    "ArmingState": ArmingState.ALARMING_CARBON_MONOXIDE,92}93PARTITION_UNKNOWN = {94    "PartitionID": "1",95    "ArmingState": "99999",96}97PARTITION_INFO_DISARMED = [PARTITION_DISARMED, PARTITION_DISARMED2]98PARTITION_INFO_ARMED_STAY = [PARTITION_ARMED_STAY, PARTITION_ARMED_STAY2]99PARTITION_INFO_ARMED_AWAY = [PARTITION_ARMED_AWAY]100PARTITION_INFO_ARMED_CUSTOM = [PARTITION_ARMED_CUSTOM]101PARTITION_INFO_ARMED_NIGHT = [PARTITION_ARMED_NIGHT]102PARTITION_INFO_ARMING = [PARTITION_ARMING]103PARTITION_INFO_DISARMING = [PARTITION_DISARMING]104PARTITION_INFO_TRIGGERED_POLICE = [PARTITION_TRIGGERED_POLICE]105PARTITION_INFO_TRIGGERED_FIRE = [PARTITION_TRIGGERED_FIRE]106PARTITION_INFO_TRIGGERED_CARBON_MONOXIDE = [PARTITION_TRIGGERED_CARBON_MONOXIDE]107PARTITION_INFO_UNKNOWN = [PARTITION_UNKNOWN]108PARTITIONS_DISARMED = {"PartitionInfo": PARTITION_INFO_DISARMED}109PARTITIONS_ARMED_STAY = {"PartitionInfo": PARTITION_INFO_ARMED_STAY}110PARTITIONS_ARMED_AWAY = {"PartitionInfo": PARTITION_INFO_ARMED_AWAY}111PARTITIONS_ARMED_CUSTOM = {"PartitionInfo": PARTITION_INFO_ARMED_CUSTOM}112PARTITIONS_ARMED_NIGHT = {"PartitionInfo": PARTITION_INFO_ARMED_NIGHT}113PARTITIONS_ARMING = {"PartitionInfo": PARTITION_INFO_ARMING}114PARTITIONS_DISARMING = {"PartitionInfo": PARTITION_INFO_DISARMING}115PARTITIONS_TRIGGERED_POLICE = {"PartitionInfo": PARTITION_INFO_TRIGGERED_POLICE}116PARTITIONS_TRIGGERED_FIRE = {"PartitionInfo": PARTITION_INFO_TRIGGERED_FIRE}117PARTITIONS_TRIGGERED_CARBON_MONOXIDE = {118    "PartitionInfo": PARTITION_INFO_TRIGGERED_CARBON_MONOXIDE119}120PARTITIONS_UNKNOWN = {"PartitionInfo": PARTITION_INFO_UNKNOWN}121ZONE_NORMAL = {122    "ZoneID": "1",123    "ZoneDescription": "Normal",124    "ZoneStatus": ZoneStatus.NORMAL,125    "PartitionId": "1",126}127ZONE_INFO = [ZONE_NORMAL]128ZONES = {"ZoneInfo": ZONE_INFO}129METADATA_DISARMED = {130    "Partitions": PARTITIONS_DISARMED,131    "Zones": ZONES,132    "PromptForImportSecuritySettings": False,133    "IsInACLoss": False,134    "IsCoverTampered": False,135    "Bell1SupervisionFailure": False,136    "Bell2SupervisionFailure": False,137    "IsInLowBattery": False,138}139METADATA_ARMED_STAY = METADATA_DISARMED.copy()140METADATA_ARMED_STAY["Partitions"] = PARTITIONS_ARMED_STAY141METADATA_ARMED_AWAY = METADATA_DISARMED.copy()142METADATA_ARMED_AWAY["Partitions"] = PARTITIONS_ARMED_AWAY143METADATA_ARMED_CUSTOM = METADATA_DISARMED.copy()144METADATA_ARMED_CUSTOM["Partitions"] = PARTITIONS_ARMED_CUSTOM145METADATA_ARMED_NIGHT = METADATA_DISARMED.copy()146METADATA_ARMED_NIGHT["Partitions"] = PARTITIONS_ARMED_NIGHT147METADATA_ARMING = METADATA_DISARMED.copy()148METADATA_ARMING["Partitions"] = PARTITIONS_ARMING149METADATA_DISARMING = METADATA_DISARMED.copy()150METADATA_DISARMING["Partitions"] = PARTITIONS_DISARMING151METADATA_TRIGGERED_POLICE = METADATA_DISARMED.copy()152METADATA_TRIGGERED_POLICE["Partitions"] = PARTITIONS_TRIGGERED_POLICE153METADATA_TRIGGERED_FIRE = METADATA_DISARMED.copy()154METADATA_TRIGGERED_FIRE["Partitions"] = PARTITIONS_TRIGGERED_FIRE155METADATA_TRIGGERED_CARBON_MONOXIDE = METADATA_DISARMED.copy()156METADATA_TRIGGERED_CARBON_MONOXIDE["Partitions"] = PARTITIONS_TRIGGERED_CARBON_MONOXIDE157METADATA_UNKNOWN = METADATA_DISARMED.copy()158METADATA_UNKNOWN["Partitions"] = PARTITIONS_UNKNOWN159RESPONSE_DISARMED = {160    "ResultCode": 0,161    "PanelMetadataAndStatus": METADATA_DISARMED,162    "ArmingState": ArmingState.DISARMED,163}164RESPONSE_ARMED_STAY = {165    "ResultCode": 0,166    "PanelMetadataAndStatus": METADATA_ARMED_STAY,167    "ArmingState": ArmingState.ARMED_STAY,168}169RESPONSE_ARMED_AWAY = {170    "ResultCode": 0,171    "PanelMetadataAndStatus": METADATA_ARMED_AWAY,172    "ArmingState": ArmingState.ARMED_AWAY,173}174RESPONSE_ARMED_CUSTOM = {175    "ResultCode": 0,176    "PanelMetadataAndStatus": METADATA_ARMED_CUSTOM,177    "ArmingState": ArmingState.ARMED_CUSTOM_BYPASS,178}179RESPONSE_ARMED_NIGHT = {180    "ResultCode": 0,181    "PanelMetadataAndStatus": METADATA_ARMED_NIGHT,182    "ArmingState": ArmingState.ARMED_STAY_NIGHT,183}184RESPONSE_ARMING = {185    "ResultCode": 0,186    "PanelMetadataAndStatus": METADATA_ARMING,187    "ArmingState": ArmingState.ARMING,188}189RESPONSE_DISARMING = {190    "ResultCode": 0,191    "PanelMetadataAndStatus": METADATA_DISARMING,192    "ArmingState": ArmingState.DISARMING,193}194RESPONSE_TRIGGERED_POLICE = {195    "ResultCode": 0,196    "PanelMetadataAndStatus": METADATA_TRIGGERED_POLICE,197    "ArmingState": ArmingState.ALARMING,198}199RESPONSE_TRIGGERED_FIRE = {200    "ResultCode": 0,201    "PanelMetadataAndStatus": METADATA_TRIGGERED_FIRE,202    "ArmingState": ArmingState.ALARMING_FIRE_SMOKE,203}204RESPONSE_TRIGGERED_CARBON_MONOXIDE = {205    "ResultCode": 0,206    "PanelMetadataAndStatus": METADATA_TRIGGERED_CARBON_MONOXIDE,207    "ArmingState": ArmingState.ALARMING_CARBON_MONOXIDE,208}209RESPONSE_UNKNOWN = {210    "ResultCode": 0,211    "PanelMetadataAndStatus": METADATA_UNKNOWN,212    "ArmingState": ArmingState.DISARMED,213}214RESPONSE_ARM_SUCCESS = {"ResultCode": ResultCode.ARM_SUCCESS.value}215RESPONSE_ARM_FAILURE = {"ResultCode": ResultCode.COMMAND_FAILED.value}216RESPONSE_DISARM_SUCCESS = {"ResultCode": ResultCode.DISARM_SUCCESS.value}217RESPONSE_DISARM_FAILURE = {218    "ResultCode": ResultCode.COMMAND_FAILED.value,219    "ResultData": "Command Failed",220}221RESPONSE_USER_CODE_INVALID = {222    "ResultCode": ResultCode.USER_CODE_INVALID.value,223    "ResultData": "testing user code invalid",224}225RESPONSE_SUCCESS = {"ResultCode": ResultCode.SUCCESS.value}226USERNAME = "username@me.com"227PASSWORD = "password"228USERCODES = {123456: "7890"}229CONFIG_DATA = {230    CONF_USERNAME: USERNAME,231    CONF_PASSWORD: PASSWORD,232    CONF_USERCODES: USERCODES,233}234CONFIG_DATA_NO_USERCODES = {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}235PARTITION_DETAILS_1 = {236    "PartitionID": 1,237    "ArmingState": ArmingState.DISARMED.value,238    "PartitionName": "Test1",239}240PARTITION_DETAILS_2 = {241    "PartitionID": 2,242    "ArmingState": ArmingState.DISARMED.value,243    "PartitionName": "Test2",244}245PARTITION_DETAILS = {"PartitionDetails": [PARTITION_DETAILS_1, PARTITION_DETAILS_2]}246RESPONSE_PARTITION_DETAILS = {247    "ResultCode": ResultCode.SUCCESS.value,248    "ResultData": "testing partition details",249    "PartitionsInfoList": PARTITION_DETAILS,250}251ZONE_DETAILS_NORMAL = {252    "PartitionId": "1",253    "Batterylevel": "-1",254    "Signalstrength": "-1",255    "zoneAdditionalInfo": None,256    "ZoneID": "1",257    "ZoneStatus": ZoneStatus.NORMAL,258    "ZoneTypeId": ZoneType.SECURITY,259    "CanBeBypassed": 1,260    "ZoneFlags": None,261}262ZONE_STATUS_INFO = [ZONE_DETAILS_NORMAL]263ZONE_DETAILS = {"ZoneStatusInfoWithPartitionId": ZONE_STATUS_INFO}264ZONE_DETAIL_STATUS = {"Zones": ZONE_DETAILS}265RESPONSE_GET_ZONE_DETAILS_SUCCESS = {266    "ResultCode": 0,267    "ResultData": "Success",268    "ZoneStatus": ZONE_DETAIL_STATUS,269}270TOTALCONNECT_REQUEST = (271    "homeassistant.components.totalconnect.TotalConnectClient.request"272)273async def setup_platform(hass, platform):274    """Set up the TotalConnect platform."""275    # first set up a config entry and add it to hass276    mock_entry = MockConfigEntry(domain=DOMAIN, data=CONFIG_DATA)277    mock_entry.add_to_hass(hass)278    responses = [279        RESPONSE_AUTHENTICATE,280        RESPONSE_PARTITION_DETAILS,281        RESPONSE_GET_ZONE_DETAILS_SUCCESS,282        RESPONSE_DISARMED,283        RESPONSE_DISARMED,284    ]285    with patch("homeassistant.components.totalconnect.PLATFORMS", [platform]), patch(286        TOTALCONNECT_REQUEST,287        side_effect=responses,288    ) as mock_request:289        assert await async_setup_component(hass, DOMAIN, {})290        assert mock_request.call_count == 5291    await hass.async_block_till_done()...quality.py
Source:quality.py  
...22    def __init__(self, G, collection):23        msg = '{} is not a valid partition of the graph {}'24        msg = msg.format(G, collection)25        super(NotAPartition, self).__init__(msg)26def is_partition(G, partition):27    """Returns True if and only if `partition` is a partition of28    the nodes of `G`.29    A partition of a universe set is a family of pairwise disjoint sets30    whose union equals the universe set.31    `G` is a NetworkX graph.32    `partition` is a sequence (not an iterator) of sets of nodes of33    `G`.34    """35    # Alternate implementation:36    #37    #     return (len(G) == sum(len(c) for c in community) and38    #             set(G) == set().union(*community))39    #40    return all(sum(1 if v in c else 0 for c in partition) == 1 for v in G)41def require_partition(func):42    """Decorator that raises an exception if a partition is not a valid43    partition of the nodes of a graph.44    Raises :exc:`networkx.NetworkXError` if the partition is not valid.45    This decorator should be used on functions whose first two arguments46    are a graph and a partition of the nodes of that graph (in that47    order)::48        >>> @require_partition49        ... def foo(G, partition):50        ...     print('partition is valid!')51        ...52        >>> G = nx.complete_graph(5)53        >>> partition = [{0, 1}, {2, 3}, {4}]54        >>> foo(G, partition)55        partition is valid!56        >>> partition = [{0}, {2, 3}, {4}]57        >>> foo(G, partition)  # doctest: +IGNORE_EXCEPTION_DETAIL58        Traceback (most recent call last):59          ...60        NetworkXError: `partition` is not a valid partition of the nodes of G61        >>> partition = [{0, 1}, {1, 2, 3}, {4}]62        >>> foo(G, partition)  # doctest: +IGNORE_EXCEPTION_DETAIL63        Traceback (most recent call last):64          ...65        NetworkXError: `partition` is not a valid partition of the nodes of G66    """67    @wraps(func)68    def new_func(*args, **kw):69        # Here we assume that the first two arguments are (G, partition).70        if not is_partition(*args[:2]):71            raise nx.NetworkXError('`partition` is not a valid partition of'72                                   ' the nodes of G')73        return func(*args, **kw)74    return new_func75def intra_community_edges(G, partition):76    """Returns the number of intra-community edges according to the given77    partition of the nodes of `G`.78    `G` must be a NetworkX graph.79    `partition` must be a partition of the nodes of `G`.80    The "intra-community edges" are those edges joining a pair of nodes81    in the same block of the partition.82    """83    return sum(G.subgraph(block).size() for block in partition)84def inter_community_edges(G, partition):85    """Returns the number of inter-community edges according to the given86    partition of the nodes of `G`.87    `G` must be a NetworkX graph.88    `partition` must be a partition of the nodes of `G`.89    The *inter-community edges* are those edges joining a pair of nodes90    in different blocks of the partition.91    Implementation note: this function creates an intermediate graph92    that may require the same amount of memory as required to store93    `G`.94    """95    # Alternate implementation that does not require constructing a new96    # graph object (but does require constructing an affiliation97    # dictionary):98    #99    #     aff = dict(chain.from_iterable(((v, block) for v in block)100    #                                    for block in partition))101    #     return sum(1 for u, v in G.edges() if aff[u] != aff[v])102    #103    return nx.quotient_graph(G, partition, create_using=nx.MultiGraph()).size()104def inter_community_non_edges(G, partition):105    """Returns the number of inter-community non-edges according to the106    given partition of the nodes of `G`.107    `G` must be a NetworkX graph.108    `partition` must be a partition of the nodes of `G`.109    A *non-edge* is a pair of nodes (undirected if `G` is undirected)110    that are not adjacent in `G`. The *inter-community non-edges* are111    those non-edges on a pair of nodes in different blocks of the112    partition.113    Implementation note: this function creates two intermediate graphs,114    which may require up to twice the amount of memory as required to115    store `G`.116    """117    # Alternate implementation that does not require constructing two118    # new graph objects (but does require constructing an affiliation119    # dictionary):120    #121    #     aff = dict(chain.from_iterable(((v, block) for v in block)122    #                                    for block in partition))123    #     return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v])124    #125    return inter_community_edges(nx.complement(G), partition)126@not_implemented_for('multigraph')127@require_partition128def performance(G, partition):129    """Returns the performance of a partition.130    The *performance* of a partition is the ratio of the number of131    intra-community edges plus inter-community non-edges with the total132    number of potential edges.133    Parameters134    ----------135    G : NetworkX graph136        A simple graph (directed or undirected).137    partition : sequence138        Partition of the nodes of `G`, represented as a sequence of139        sets of nodes. Each block of the partition represents a140        community.141    Returns142    -------143    float144        The performance of the partition, as defined above.145    Raises146    ------147    NetworkXError148        If `partition` is not a valid partition of the nodes of `G`.149    References150    ----------151    .. [1] Santo Fortunato.152           "Community Detection in Graphs".153           *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174154           <http://arxiv.org/abs/0906.0612>155    """156    # Compute the number of intra-community edges and inter-community157    # edges.158    intra_edges = intra_community_edges(G, partition)159    inter_edges = inter_community_non_edges(G, partition)160    # Compute the number of edges in the complete graph (directed or161    # undirected, as it depends on `G`) on `n` nodes.162    #163    # (If `G` is an undirected graph, we divide by two since we have164    # double-counted each potential edge. We use integer division since165    # `total_pairs` is guaranteed to be even.)166    n = len(G)167    total_pairs = n * (n - 1)168    if not G.is_directed():169        total_pairs //= 2170    return (intra_edges + inter_edges) / total_pairs171@require_partition172def coverage(G, partition):173    """Returns the coverage of a partition.174    The *coverage* of a partition is the ratio of the number of175    intra-community edges to the total number of edges in the graph.176    Parameters177    ----------178    G : NetworkX graph179    partition : sequence180        Partition of the nodes of `G`, represented as a sequence of181        sets of nodes. Each block of the partition represents a182        community.183    Returns184    -------185    float186        The coverage of the partition, as defined above.187    Raises188    ------189    NetworkXError190        If `partition` is not a valid partition of the nodes of `G`.191    Notes192    -----193    If `G` is a multigraph, the multiplicity of edges is counted.194    References195    ----------196    .. [1] Santo Fortunato.197           "Community Detection in Graphs".198           *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174199           <http://arxiv.org/abs/0906.0612>200    """201    intra_edges = intra_community_edges(G, partition)202    total_edges = G.number_of_edges()203    return intra_edges / total_edges204def modularity(G, communities, weight='weight'):205    r"""Returns the modularity of the given partition of the graph.206    Modularity is defined in [1]_ as207    .. math::208        Q = \frac{1}{2m} \sum_{ij} \left( A_{ij} - \frac{k_ik_j}{2m}\right)209            \delta(c_i,c_j)210    where *m* is the number of edges, *A* is the adjacency matrix of211    `G`, :math:`k_i` is the degree of *i* and :math:`\delta(c_i, c_j)`212    is 1 if *i* and *j* are in the same community and 0 otherwise.213    Parameters214    ----------215    G : NetworkX Graph216    communities : list217        List of sets of nodes of `G` representing a partition of the218        nodes.219    Returns220    -------221    Q : float222        The modularity of the paritition.223    Raises224    ------225    NotAPartition226        If `communities` is not a partition of the nodes of `G`.227    Examples228    --------229    >>> G = nx.barbell_graph(3, 0)230    >>> nx.modularity(G, [{0, 1, 2}, {3, 4, 5}])231    0.35714285714285704232    References233    ----------234    .. [1] M. E. J. Newman *Networks: An Introduction*, page 224.235       Oxford University Press, 2011.236    """237    if not is_partition(G, communities):238        raise NotAPartition(G, communities)239    multigraph = G.is_multigraph()240    directed = G.is_directed()241    m = G.size(weight=weight)242    if directed:243        out_degree = dict(G.out_degree(weight=weight))244        in_degree = dict(G.in_degree(weight=weight))245        norm = 1 / m246    else:247        out_degree = dict(G.degree(weight=weight))248        in_degree = out_degree249        norm = 1 / (2 * m)250    def val(u, v):251        try:...test_partitions.py
Source:test_partitions.py  
...192            user_tags_service=self.user_tags_service,193            course_id=Mock(),194            track_function=Mock()195        )196    def test_get_user_group_for_partition(self):197        # get a group assigned to the user198        group1 = self.partitions_service.get_user_group_for_partition(self.partition_id)199        # make sure we get the same group back out if we try a second time200        group2 = self.partitions_service.get_user_group_for_partition(self.partition_id)201        self.assertEqual(group1, group2)202        # test that we error if given an invalid partition id203        with self.assertRaises(ValueError):204            self.partitions_service.get_user_group_for_partition(3)205    def test_user_in_deleted_group(self):206        # get a group assigned to the user - should be group 0 or 1207        old_group = self.partitions_service.get_user_group_for_partition(self.partition_id)208        self.assertIn(old_group, [0, 1])209        # Change the group definitions! No more group 0 or 1210        groups = [Group(3, 'Group 3'), Group(4, 'Group 4')]211        user_partition = UserPartition(self.partition_id, 'Test Partition', 'for testing purposes', groups)212        self.partitions_service = StaticPartitionService(213            [user_partition],214            user_tags_service=self.user_tags_service,215            course_id=Mock(),216            track_function=Mock()217        )218        # Now, get a new group using the same call - should be 3 or 4219        new_group = self.partitions_service.get_user_group_for_partition(self.partition_id)220        self.assertIn(new_group, [3, 4])221        # We should get the same group over multiple calls222        new_group_2 = self.partitions_service.get_user_group_for_partition(self.partition_id)223        self.assertEqual(new_group, new_group_2)224    def test_change_group_name(self):225        # Changing the name of the group shouldn't affect anything226        # get a group assigned to the user - should be group 0 or 1227        old_group = self.partitions_service.get_user_group_for_partition(self.partition_id)228        self.assertIn(old_group, [0, 1])229        # Change the group names230        groups = [Group(0, 'Group 0'), Group(1, 'Group 1')]231        user_partition = UserPartition(self.partition_id, 'Test Partition', 'for testing purposes', groups)232        self.partitions_service = StaticPartitionService(233            [user_partition],234            user_tags_service=self.user_tags_service,235            course_id=Mock(),236            track_function=Mock()237        )238        # Now, get a new group using the same call239        new_group = self.partitions_service.get_user_group_for_partition(self.partition_id)...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!!
