コード例 #1
0
async def cancel(session: CommandSession):
    global l
    if int(session.ctx['user_id']) in blacklist:
        return
    l2 = more_itertools.only(
        [x for x in enumerate(l) if x[1].name == session.current_arg_text])
    if l2 is None:
        l2 = more_itertools.only([
            x for x in enumerate(l)
            if str(x[1].id) == session.current_arg_text.strip()
        ])
        if l2 is None:
            await session.send('未找到')
            return
    i = l2[0]
    if int(session.ctx['user_id']) == l[i].qq or \
            await permission.check_permission(get_bot(), session.ctx, permission.GROUP_ADMIN):
        now = datetime.now()
        e = l.pop(i)
        await _save(l)
        if e.supervise != 0 and (
                not e.isFloat and e.begin < now < e.end or e.isFloat and
            (i == len(l) - 1 or e.begin < now < l[i + 1].begin)):
            d = ((now - e.begin).total_seconds() - 1) // 60 + 1
            if add_time(e.qq, d):
                await session.send('您已成功通过试用期转正!')
        await _save(l)
        await session.send('成功删除')
        ret = await change_des_to_list()
        if json.loads(ret)['code'] != 0:
            await session.send('更新到直播间失败')
    else:
        await session.send('非管理员不可删除别人的')
コード例 #2
0
    def visitBoot_stanza(
            self, ctx: RefindConfigParser.Boot_stanzaContext) -> BootStanza:
        menu_entry_context = ctx.menu_entry()
        menu_entry = menu_entry_context.accept(MenuEntryVisitor())
        main_options = OptionVisitor.map_to_options_dict(
            checked_cast(list[ParserRuleContext], ctx.main_option()))
        volume = only(always_iterable(main_options.get(RefindOption.VOLUME)))
        loader = only(always_iterable(main_options.get(RefindOption.LOADER)))
        initrd = only(always_iterable(main_options.get(RefindOption.INITRD)))
        icon = only(always_iterable(main_options.get(RefindOption.ICON)))
        os_type = only(always_iterable(main_options.get(RefindOption.OS_TYPE)))
        graphics = only(
            always_iterable(main_options.get(RefindOption.GRAPHICS)))
        boot_options = only(
            always_iterable(main_options.get(RefindOption.BOOT_OPTIONS)))
        firmware_bootnum = only(
            always_iterable(main_options.get(RefindOption.FIRMWARE_BOOTNUM)))
        disabled = only(always_iterable(main_options.get(
            RefindOption.DISABLED)),
                        default=False)
        sub_menus = always_iterable(
            main_options.get(RefindOption.SUB_MENU_ENTRY))

        return BootStanza(
            menu_entry,
            volume,
            loader,
            initrd,
            icon,
            os_type,
            graphics,
            BootOptions(boot_options),
            firmware_bootnum,
            disabled,
        ).with_sub_menus(sub_menus)
コード例 #3
0
ファイル: model.py プロジェクト: kalekundert/freezerbox
    def get_seq(self):
        # Explicitly cache this property, rather than relying on the caching
        # provided by autoprop.  We go out of our way to do this because (i)
        # the sequence is especially expensive to look up and (ii) we know that
        # it won't be affected by the cleanup steps.

        if self._seq:
            return self._seq

        seq = self._attrs.get('seq')

        # Allow the retrieval of the sequence to be deferred, e.g. so unused
        # sequences never have to be read from disc.
        if callable(seq):
            seq = seq()

        # If we have instructions for how to make this molecule, try getting
        # the sequence from that.
        if not seq:
            seq = only(
                self.get_synthesis_attr('product_seqs', []),
                too_long=QueryError("protocol has multiple sequences",
                                    culprit=self),
            )

        if not seq:
            raise QueryError("no sequence specified", culprit=self)

        self._seq = seq
        return seq
コード例 #4
0
    def _is_snapshot_deleted(self, deleted_directory: Path) -> bool:
        persistence_provider = self._persistence_provider
        previous_run_result = persistence_provider.get_previous_run_result()
        bootable_snapshots = previous_run_result.bootable_snapshots

        if has_items(bootable_snapshots):
            deleted_snapshot = only(
                snapshot for snapshot in bootable_snapshots
                if snapshot.is_located_in(deleted_directory))

            if deleted_snapshot is not None:
                deleted_snapshots = self._deleted_snapshots
                deletion_lock = self._deletion_lock

                with deletion_lock:
                    if deleted_snapshot not in deleted_snapshots:
                        snapshot_manipulation = (
                            self.package_config.snapshot_manipulation)
                        cleanup_exclusion = snapshot_manipulation.cleanup_exclusion

                        deleted_snapshots.add(deleted_snapshot)

                        if deleted_snapshot in cleanup_exclusion:
                            raise SnapshotExcludedFromDeletionError(
                                f"The deleted snapshot ('{deleted_directory}') "
                                "is explicitly excluded from cleanup!")

                        return True

        return False
コード例 #5
0
ファイル: config.py プロジェクト: kalekundert/stepwise
        def iter_values(self, key, log):
            layer_1 = appcli.DictLayer(self.presets_getter())
            preset = only(layer_1.iter_values(self.key_getter(), log))

            if preset is not None:
                layer_2 = appcli.DictLayer(preset, schema=self.schema)
                yield from layer_2.iter_values(key, log)
コード例 #6
0
def test_matching_static_vs_dynamic_graphs():
    target_object = BOX
    train_obj_object = object_variable("obj-with-color", target_object)
    obj_template = Phase1SituationTemplate(
        "colored-obj-object", salient_object_variables=[train_obj_object])
    template = all_possible(obj_template,
                            chooser=PHASE1_CHOOSER_FACTORY(),
                            ontology=GAILA_PHASE_1_ONTOLOGY)
    train_curriculum = phase1_instances("all obj situations",
                                        situations=template)
    perceptual_representation = only(train_curriculum.instances())[2]

    perception_graph = graph_without_learner(
        PerceptionGraph.from_frame(perceptual_representation.frames[0]))
    temporal_perception_graph = perception_graph.copy_with_temporal_scopes(
        temporal_scopes=[TemporalScope.AFTER])

    perception_pattern = PerceptionGraphPattern.from_graph(
        perception_graph).perception_graph_pattern

    temporal_perception_pattern = perception_pattern.copy_with_temporal_scopes(
        required_temporal_scopes=[TemporalScope.AFTER])

    # Test runtime error for matching static pattern against dynamic graph and vice versa

    with pytest.raises(RuntimeError):
        perception_pattern.matcher(temporal_perception_graph,
                                   match_mode=MatchMode.NON_OBJECT)

    with pytest.raises(RuntimeError):
        temporal_perception_pattern.matcher(perception_graph,
                                            match_mode=MatchMode.NON_OBJECT)
コード例 #7
0
def get_sd_person_changed(
    identifier_type: IdType, identifier: str, xml_root: _Element
) -> SdPersonChange:

    # Get the request date timestamps
    request_structure = xml_root.find("RequestStructure")
    activation_date = request_structure.find("ActivationDate").text.strip()
    deactivation_date = request_structure.find("DeactivationDate").text.strip()

    def id_match(id_type: IdType, id_: str, person: _Element) -> bool:
        if id_type == IdType.CPR:
            id_element = person.find(id_type.value)
        else:
            employment_element = person.find("Employment")
            id_element = employment_element.find(id_type.value)

        if id_ == id_element.text.strip():
            return True
        return False

    person_elements = xml_root.findall("Person")
    persons = filter(partial(id_match, identifier_type, identifier), person_elements)

    sd_person_changed = SdPersonChange(
        start_date=activation_date, end_date=deactivation_date, change=only(persons)
    )

    return sd_person_changed
コード例 #8
0
 def _compute_axis_info(
     self,
     object_var_to_instantiations: Mapping[TemplateObjectVariable,
                                           SituationObject],
 ) -> AxesInfo[SituationObject]:
     # if there is an addressee, then we determine which axis
     # of each object faces the addressee
     addressees = immutableset(
         obj for obj in object_var_to_instantiations.values()
         if IS_ADDRESSEE in obj.properties)
     if addressees:
         if len(addressees) > 1:
             raise RuntimeError("Multiple addressees not supported")
         else:
             addressee: SituationObject = only(addressees)
             return AxesInfo(
                 addressee=addressee,
                 axes_facing=[
                     (
                         addressee,
                         # TODO: fix this hack
                         HorizontalAxisOfObject(  # type: ignore
                             obj, index=1).to_concrete_axis(None),
                     ) for obj in object_var_to_instantiations.values()
                     if obj.axes
                 ],
             )
     else:
         return AxesInfo()
コード例 #9
0
    def required_action_description(
            self, action_type: OntologyNode,
            semantic_roles: Iterable[OntologyNode]) -> ActionDescription:
        semantic_roles_set = immutableset(semantic_roles)
        descriptions_for_action_type = self.action_to_description[action_type]
        matching_descriptions = immutableset(
            description for description in descriptions_for_action_type
            if description.frame.semantic_roles == semantic_roles_set)

        if matching_descriptions:
            if len(matching_descriptions) == 1:
                return only(matching_descriptions)
            else:
                raise RuntimeError(
                    f"Multiple action descriptions match action type "
                    f"{action_type} and roles {semantic_roles_set}")
        else:
            available_frames: Any = [
                immutableset(description.frame.roles_to_variables.keys())
                for description in descriptions_for_action_type
            ]
            raise RuntimeError(
                f"No action descriptions match action type "
                f"{action_type} and roles {semantic_roles_set}. "
                f"Known frames for {action_type} are "
                f"{available_frames}")
コード例 #10
0
 def has_it_system(uuid, ad_object):
     mo_itsystem_uuid = self.mapping["it_systems"][
         "samAccountName"]
     itconnections = self._read_itconnections(
         uuid, mo_itsystem_uuid)
     mo_username, _ = only(itconnections, ("", ""))
     return mo_username != ""
コード例 #11
0
    def to_concrete_axis(
        self, axes_info: Optional[AxesInfo[_ObjectT]]  # pylint:disable=unused-argument
    ) -> GeonAxis:
        if not axes_info:
            raise RuntimeError(
                "FacingAddresseeAxis cannot be applied if axis info not available"
            )
        if not isinstance(self._object, HasAxes):
            raise RuntimeError(
                "Can only instantiate an axis function if the object is of a "
                "concrete type (e.g. perception or situation object)"
            )
        addressee: Optional[_ObjectT] = axes_info.addressee
        if not addressee:
            raise RuntimeError("Addressee must be specified to use FacingAddresseeAxis")
        object_axes = immutableset(self._object.axes.all_axes)
        object_axes_facing_addressee = axes_info.axes_facing[addressee].intersection(
            object_axes
        )

        if object_axes_facing_addressee:
            if len(object_axes_facing_addressee) == 1:
                return only(object_axes_facing_addressee)
            else:
                raise RuntimeError("Cannot handle multiple axes facing the addressee.")
        else:
            raise RuntimeError(
                f"Could not find axis of {self._object} facing addressee {addressee}. Axis info is "
                f"{axes_info}.  Axes of object is {object_axes}"
            )
コード例 #12
0
def test_successfully_extending_partial_match():
    """
    Tests whether we can match a perception pattern against a perception graph
    when initializing the search from a partial match.
    """

    target_object = BOX
    # Create train and test templates for the target objects
    train_obj_object = object_variable("obj-with-color", target_object)

    obj_template = Phase1SituationTemplate(
        "colored-obj-object", salient_object_variables=[train_obj_object])
    template = all_possible(obj_template,
                            chooser=PHASE1_CHOOSER_FACTORY(),
                            ontology=GAILA_PHASE_1_ONTOLOGY)

    train_curriculum = phase1_instances("all obj situations",
                                        situations=template)

    perceptual_representation = only(train_curriculum.instances())[2]

    # Original perception graph
    perception = PerceptionGraph.from_frame(
        perceptual_representation.frames[0])

    # Create a perception pattern for the whole thing
    # and also a perception pattern for a subset of the whole pattern
    whole_perception_pattern = PerceptionGraphPattern.from_graph(
        perception).perception_graph_pattern

    partial_digraph = whole_perception_pattern.copy_as_digraph()
    partial_digraph.remove_nodes_from([
        node for node in partial_digraph.nodes
        if isinstance(node, IsColorNodePredicate)
    ])
    partial_perception_pattern = PerceptionGraphPattern(partial_digraph)

    # get our initial match by matching the partial pattern
    matcher = partial_perception_pattern.matcher(
        perception, match_mode=MatchMode.NON_OBJECT)

    partial_match: PerceptionGraphPatternMatch = first(
        matcher.matches(use_lookahead_pruning=True))
    partial_mapping = partial_match.pattern_node_to_matched_graph_node

    # Try to extend the partial mapping, to create a complete mapping
    matcher_2 = whole_perception_pattern.matcher(
        perception, match_mode=MatchMode.NON_OBJECT)
    complete_match: PerceptionGraphPatternMatch = first(
        matcher_2.matches(initial_partial_match=partial_mapping,
                          use_lookahead_pruning=True),
        None,
    )
    complete_mapping = complete_match.pattern_node_to_matched_graph_node
    assert len(complete_mapping) == len(perception.copy_as_digraph().nodes)
    assert len(complete_mapping) == len(
        whole_perception_pattern.copy_as_digraph().nodes)
コード例 #13
0
 def __init__(self, id):
     #with open(config.rel(f'games\\snakebird\\{id}.txt')) as f:
     with open(f'C:\\\coolq_data\\games\\snakebird\\{id}.txt') as f:
         self.board = [list(line.strip()) for line in f.readlines()]
     self.border = ((0, len(self.board)), (0, len(self.board[0])))
     # 0: blank 1: wall 2: food 3: spike 8: portal 9: end Aaa: snake IIIJJ: block Z: void T: tail
     _head = dict([(c,
                    more_itertools.only([
                        (i, line.index(c))
                        for i, line in enumerate(self.board) if c in line
                    ])) for c in 'ABC'])
     self.snake = {}  # 蛇头在list尾部
     for c, head in _head.items():
         if head is None:
             continue
         self.snake[c] = [head]
         t = head
         while 1:
             for dir in self.dir:
                 s = add(t, dir)
                 if in_border(s, self.border) and self[s] == c.lower(
                 ) and s not in self.snake[c]:
                     self.snake[c] = [s] + self.snake[c]
                     t = s
                     break
             else:
                 break
     self.cal_food()
     self.win = more_itertools.only([(i, line.index('9'))
                                     for i, line in enumerate(self.board)
                                     if '9' in line])
     self[self.win] = '0'
     self.portal = functools.reduce(
         lambda x, y: x + y,
         [[(i, j) for j in more_itertools.locate(line, lambda x: x == '8')]
          for i, line in enumerate(self.board)])
     assert (len(self.portal) in {0, 2})
     if len(self.portal) == 2:
         self[self.portal[0]] = self[self.portal[1]] = '0'
     self.block = {}  # TODO
     self.stack = []
     self.activate = 'A'
コード例 #14
0
ファイル: param_helpers.py プロジェクト: kalekundert/appcli
def find_param(obj, name=None):
    from more_itertools import only
    class_attrs = obj.__class__.__dict__

    if name:
        return class_attrs[name]
    else:
        params = (x for x in class_attrs.values() if isinstance(x, byoc.param))
        default = byoc.param()
        default.__set_name__(obj.__class__, '')
        return only(params, default)
コード例 #15
0
    def visitSub_menu(self,
                      ctx: RefindConfigParser.Sub_menuContext) -> SubMenu:
        menu_entry_context = ctx.menu_entry()
        menu_entry = menu_entry_context.accept(MenuEntryVisitor())
        sub_options = OptionVisitor.map_to_options_dict(
            checked_cast(list[ParserRuleContext], ctx.sub_option()))
        loader = only(always_iterable(sub_options.get(RefindOption.LOADER)))
        initrd = only(always_iterable(sub_options.get(RefindOption.INITRD)))
        graphics = only(always_iterable(sub_options.get(
            RefindOption.GRAPHICS)))
        boot_options = only(
            always_iterable(sub_options.get(RefindOption.BOOT_OPTIONS)))
        add_boot_options = only(
            always_iterable(sub_options.get(RefindOption.ADD_BOOT_OPTIONS)))
        disabled = only(always_iterable(sub_options.get(
            RefindOption.DISABLED)),
                        default=False)

        return SubMenu(
            menu_entry,
            loader,
            initrd,
            graphics,
            BootOptions(boot_options) if boot_options is not None else None,
            BootOptions(add_boot_options),
            disabled,
        )
def test_perceive_explicit_relations():
    # we want to test that relations explicitly called out in the situation are perceived.
    # Such relations fall into three buckets:
    # those which hold before an action,
    # those which hold after an action,
    # and those which hold both before and after an action.
    # To test all three of these at once, we use a situation where
    # (a) Mom is putting a ball on a table
    # (b) before the action the ball is far from a box,
    # (c) but after the action the ball is near the box,
    # (d) throughout the action the box is on the table.
    mom = situation_object(MOM)
    ball = situation_object(BALL)
    box = situation_object(BOX)
    table = situation_object(TABLE)
    situation = HighLevelSemanticsSituation(
        ontology=GAILA_PHASE_1_ONTOLOGY,
        salient_objects=[mom, box, ball, table],
        always_relations=[on(ball, table)],
        before_action_relations=[far(ball, box)],
        after_action_relations=[near(ball, box)],
        actions=[
            Action(
                PUT,
                argument_roles_to_fillers=[
                    (AGENT, mom),
                    (THEME, ball),
                    (
                        GOAL,
                        Region(
                            reference_object=table,
                            distance=EXTERIOR_BUT_IN_CONTACT,
                            direction=GRAVITATIONAL_UP,
                        ),
                    ),
                ],
            )
        ],
    )
    perception = _PERCEPTION_GENERATOR.generate_perception(
        situation, chooser=RandomChooser.for_seed(0)
    )

    ball_perception = perception_with_handle(perception.frames[0], "**ball_0")
    box_perception = perception_with_handle(perception.frames[0], "**box_0")
    table_perception = perception_with_handle(perception.frames[0], "**table_0")

    assert only(on(ball_perception, table_perception)) in perception.frames[0].relations
    assert only(on(ball_perception, table_perception)) in perception.frames[0].relations

    assert only(far(ball_perception, box_perception)) in perception.frames[0].relations
    assert (
        only(far(ball_perception, box_perception)) not in perception.frames[1].relations
    )

    assert (
        only(near(ball_perception, box_perception)) not in perception.frames[0].relations
    )
    assert only(near(ball_perception, box_perception)) in perception.frames[1].relations
コード例 #17
0
    def __init__(self):

        self.settings = load_settings()
        self.root_ou_uuid = self.settings["integrations.ad.import_ou.mo_unit_uuid"]
        self.helper = MoraHelper(hostname=self.settings["mora.base"], use_cache=False)
        self.org_uuid = self.helper.read_organisation()

        self.ad_reader = ADParameterReader()
        self.ad_reader.cache_all(print_progress=True)

        its = self.helper.read_it_systems()
        AD_its = only(filter(lambda x: x["name"] == constants.AD_it_system, its))
        self.AD_it_system_uuid = AD_its["uuid"]
コード例 #18
0
def find_type(opus_id, full_history):
    """Check if the object with the given id is a unit or an employee."""
    dumps = get_opus_filereader().list_opus_files()
    # Search in newest file first
    opus_files = sorted(dumps, reverse=True)
    if not full_history:
        opus_files = [first(opus_files)]
    for f in opus_files:
        units, employees = opus_helpers.parser(dumps[f], opus_id=opus_id)
        employees, terminated_employees = opus_helpers.split_employees_leaves(
            employees)
        employees = list(employees)
        if units:
            return "organisationenhed", only(units)
        elif employees:
            return "bruger", only(employees)

    terminated_employees = list(terminated_employees)
    if terminated_employees:
        msg = "Employee was terminated, try --full-history"
    else:
        msg = f"No object with {opus_id=} was found."
    raise ValueError(msg)
コード例 #19
0
ファイル: transform.py プロジェクト: NoopDog/azul
    def from_index(self, value: str) -> Optional[JSON]:
        """
        >>> a = ValueAndUnit()
        >>> a.from_index('20 year')
        {'value': '20', 'unit': 'year'}

        >>> a.from_index('20')
        {'value': '20', 'unit': None}

        >>> a.from_index('~null') is None
        True

        Although 'year' looks like a unit, we intentionally treat it like a
        value because this class does not enforce any constraints on value or
        unit other than it not contain spaces.

        >>> a.from_index('year')
        {'value': 'year', 'unit': None}

        >>> a.from_index('20  ')
        Traceback (most recent call last):
        ...
        ValueError: too many items in iterable (expected 1)

        >>> a.from_index(' year')
        Traceback (most recent call last):
        ...
        AssertionError

        >>> a.from_index('1 ')
        Traceback (most recent call last):
        ...
        AssertionError

        >>> a.from_index('')
        Traceback (most recent call last):
        ...
        AssertionError
        """
        if value == NullableString.null_string:
            return None
        else:
            i = iter(value.split(' '))
            value = next(i)
            # only() fails with more than one item left in the iterator
            unit = only(i)
            assert value, value
            assert unit is None or unit, unit
            return {'value': value, 'unit': unit}
コード例 #20
0
def check_relations(
    session,
    base: str,
    uuid: UUID,
    relation_type: str = "organisation/organisationfunktion",
) -> List[dict]:
    """Find all objects related to the class with the given uuid.

    Returns a list of objects, or an empty list if no objects related to the given uuid are found.
    """
    r = session.get(
        base +
        f"/{relation_type}?vilkaarligrel={str(uuid)}&list=true&virkningfra=-infinity"
    )
    r.raise_for_status()
    res = r.json()["results"]
    return only(res, default=[])
コード例 #21
0
    def _edit_it_system(self, uuid, ad_object):
        mo_itsystem_uuid = self.mapping["it_systems"]["samAccountName"]
        itconnections = self._read_itconnections(uuid, mo_itsystem_uuid)
        # Here it_systems is a 2 tuple (mo_username, binding_uuid)
        mo_username, binding_uuid = only(itconnections, ("", ""))
        # Username currently in AD
        ad_username = ad_object["SamAccountName"]

        # If mo_username is blank, we found a user who needs a new entry created
        if mo_username == "":
            self._create_it_system(uuid, ad_username, mo_itsystem_uuid)
            self.stats["it_systems"] += 1
            self.stats["users"].add(uuid)
        elif mo_username != ad_username:  # We need to update the mo_username
            self._update_it_system(ad_username, binding_uuid)
            self.stats["it_systems"] += 1
            self.stats["users"].add(uuid)
def test_path_from_action_description():
    ball = situation_object(BALL)
    situation = HighLevelSemanticsSituation(
        ontology=GAILA_PHASE_1_ONTOLOGY,
        salient_objects=[ball],
        actions=[Action(FALL, argument_roles_to_fillers=[(THEME, ball)])],
    )
    perception = _PERCEPTION_GENERATOR.generate_perception(
        situation, chooser=RandomChooser.for_seed(0)
    )
    ball_perception = perception_with_handle(perception.frames[0], "**ball_0")
    ground_perception = perception_with_handle(perception.frames[0], "the ground")
    assert perception.during
    assert perception.during.objects_to_paths
    assert len(perception.during.objects_to_paths) == 1
    path = only(perception.during.objects_to_paths[ball_perception])
    assert path.reference_object == ground_perception
    assert path.operator == TOWARD
コード例 #23
0
    def instantiate_ontology_node(
        ontology_node: OntologyNode,
        *,
        properties: Iterable[OntologyNode] = immutableset(),
        debug_handle: Optional[str] = None,
        ontology: Ontology,
    ) -> "SituationObject":
        """
        Make a `SituationObject` from the object type *ontology_node*
        with properties *properties*.
        The *properties* and ontology node must all come from *ontology*.
        """
        schema_axis_to_object_axis: Mapping[GeonAxis, GeonAxis]
        if ontology.has_property(ontology_node, IS_SUBSTANCE):
            # it's not clear what the object_concrete_axes should be for substances,
            # so we just use the world object_concrete_axes for now
            schema_axis_to_object_axis = immutabledict()
            object_concrete_axes = WORLD_AXES
        else:
            structural_schemata = ontology.structural_schemata(ontology_node)
            if not structural_schemata:
                raise RuntimeError(
                    f"No structural schema found for {ontology_node}")
            if len(structural_schemata) > 1:
                raise RuntimeError(
                    f"Multiple structural schemata available for {ontology_node}, "
                    f"please construct the SituationObject manually: "
                    f"{structural_schemata}")
            schema_abstract_axes = only(structural_schemata).axes
            # The copy is needed or e.g. all tires of a truck
            # would share the same axis objects.
            object_concrete_axes = schema_abstract_axes.copy()
            schema_axis_to_object_axis = immutabledict(
                zip(schema_abstract_axes.all_axes,
                    object_concrete_axes.all_axes))

        return SituationObject(
            ontology_node=ontology_node,
            properties=properties,
            debug_handle=debug_handle
            if debug_handle else ontology_node.handle,
            axes=object_concrete_axes,
            schema_axis_to_object_axis=schema_axis_to_object_axis,
        )
コード例 #24
0
def test_perception_graph_post_init_edge_cases():
    target_object = BOX
    train_obj_object = object_variable("obj-with-color", target_object)
    obj_template = Phase1SituationTemplate(
        "colored-obj-object", salient_object_variables=[train_obj_object])
    template = all_possible(obj_template,
                            chooser=PHASE1_CHOOSER_FACTORY(),
                            ontology=GAILA_PHASE_1_ONTOLOGY)
    train_curriculum = phase1_instances("all obj situations",
                                        situations=template)
    perceptual_representation = only(train_curriculum.instances())[2]
    perception_graph = graph_without_learner(
        PerceptionGraph.from_frame(perceptual_representation.frames[0]))
    temporal_perception_graph = perception_graph.copy_with_temporal_scopes(
        temporal_scopes=[TemporalScope.AFTER])
    temporal_digraph = temporal_perception_graph.copy_as_digraph()
    # Test valid edge label
    # The only feasible test seems to be the instation, since creating a corrupt instance throws the same RuntimeError
    with pytest.raises(RuntimeError):
        TemporallyScopedEdgeLabel(None)

    # In a dynamic graph, all edge labels must be wrapped in TemporallyScopedEdgeLabel
    new_graph = DiGraph()
    for (source, target) in temporal_digraph.edges():
        new_graph.add_edge(source, target)
        new_graph[source][target]["label"] = None
    with pytest.raises(RuntimeError):
        PerceptionGraph(new_graph, dynamic=True)

    # TemporallyScopedEdgeLabels may not appear in a static graph
    new_graph = DiGraph()
    for (source, target) in temporal_digraph.edges():
        new_graph.add_edge(source, target)
        new_graph[source][target]["label"] = TemporallyScopedEdgeLabel(
            "attribute", [TemporalScope.AFTER])
    with pytest.raises(RuntimeError):
        PerceptionGraph(new_graph)

    # Every edge in a PerceptionGraph must have a 'label
    new_graph = DiGraph()
    for (source, target) in temporal_digraph.edges():
        new_graph.add_edge(source, target)
    with pytest.raises(RuntimeError):
        PerceptionGraph(new_graph)
コード例 #25
0
async def thwiki_supervise(session: CommandSession):
    group_id = session.ctx['group_id']
    if group_id not in config.group_id_dict['thwiki_supervise']:
        return
    qq = session.ctx['user_id']
    i = session.current_arg_text.split(' ')
    if len(i) == 1:
        id = int(i[0])
        t = True
    elif len(i) == 2:
        id = int(i[0])
        t = not (i[1] == 'false' or i[1] == 'False' or i[1] == 'f'
                 or i[1] == 'F')
    else:
        await session.send('使用-thwiki.supervise 直播id [可选:True/False]')
        return
    ret = more_itertools.only([x for x in l if x.id == id])
    if ret is None:
        await session.send('未发现此id的直播提交')
    elif ret.supervise == -1:
        await session.send('此直播提交者已有权限')
    elif ret.supervise > 0 and t:
        await session.send('此直播提交已有监视者')
    elif ret.supervise != qq and not t:
        await session.send('删除失败')
    else:
        if t:
            ret.supervise = qq
            if ret.begin < datetime.now():
                ret.begin = datetime.now()
            await _save(l)
            await session.send('成功提交监视')
            for group in config.group_id_dict['thwiki_send']:
                await get_bot().send_group_msg(group_id=group,
                                               message=ret.str_with_at())
        else:
            ret.supervise = 0
            await _save(l)
            await session.send('成功删除监视')
            for group in config.group_id_dict['thwiki_send']:
                await get_bot().send_group_msg(group_id=group,
                                               message=ret.str_with_at())
コード例 #26
0
    def connect_it_system(self, username, it_system, employee, person_uuid):
        it_system_uuid = self.it_systems[it_system]
        current = self.helper.get_e_itsystems(person_uuid,
                                              it_system_uuid=it_system_uuid)
        try:
            current = only(current, default={})
        except ValueError:
            logger.warning(
                f"Skipped connecting {it_system} IT system . More than one IT system found for {person_uuid=}"
            )
            return

        if not (username or current):
            return
        # New it-system account
        if not current:
            payload = payloads.connect_it_system_to_user(
                username,
                it_system_uuid,
                person_uuid,
                self.xml_date.strftime("%Y-%m-%d"),
            )
            logger.debug(f"{it_system} account payload: {payload}")
            response = self.helper._mo_post("details/create", payload)
            assert response.status_code == 201
            logger.info(f"Added {it_system} info for {person_uuid}")
        # Deleted it-system account
        elif not username:
            self.terminate_detail(current["uuid"], detail_type="it")
            logger.info(f"No {it_system} info for {person_uuid} any longer")
        # Changed account name. Only supports one account pr it-system
        elif current.get("user_key") != username:
            payload = payloads.edit_it_system_username(
                current["uuid"],
                username,
                self.xml_date.strftime("%Y-%m-%d"),
            )
            logger.debug(f"{it_system} account payload: {payload}")
            response = self.helper._mo_post("details/edit", payload)
            response.raise_for_status()
            logger.info(f"Changed {it_system} info for {person_uuid}")
コード例 #27
0
def test_copy_with_temporal_scopes_content():
    """
    Tests whether copy_with_temporal_scopes converts graphs to be dynamic as intended
    """

    # We use a situation to generate the perceptual representation
    # for a box with color.
    target_object = BOX
    train_obj_object = object_variable("obj-with-color", target_object)
    obj_template = Phase1SituationTemplate(
        "colored-obj-object", salient_object_variables=[train_obj_object])
    template = all_possible(obj_template,
                            chooser=PHASE1_CHOOSER_FACTORY(),
                            ontology=GAILA_PHASE_1_ONTOLOGY)

    train_curriculum = phase1_instances("all obj situations",
                                        situations=template)

    perceptual_representation = only(train_curriculum.instances())[2]

    perception_graph = graph_without_learner(
        PerceptionGraph.from_frame(perceptual_representation.frames[0]))
    temporal_perception_graph = perception_graph.copy_with_temporal_scopes(
        temporal_scopes=[TemporalScope.AFTER])
    for (source, target) in perception_graph.copy_as_digraph().edges():
        assert not isinstance(
            perception_graph.copy_as_digraph()[source][target]["label"],
            TemporallyScopedEdgeLabel,
        )
    for (source,
         target) in temporal_perception_graph.copy_as_digraph().edges():
        # Check type, and then the content
        label = temporal_perception_graph.copy_as_digraph(
        )[source][target]["label"]
        assert isinstance(label, TemporallyScopedEdgeLabel)
        assert (label.attribute == perception_graph.copy_as_digraph()[source]
                [target]["label"])
        assert all(specifier in [TemporalScope.AFTER]
                   for specifier in label.temporal_specifiers)
コード例 #28
0
def pretty_descriptions(
    descriptions: Mapping[LinguisticDescription, float],
    num_descriptions: int,
    *,
    sort_by_length: bool,
) -> str:
    if len(descriptions) > 1:
        top_descriptions = take(
            num_descriptions,
            sorted(descriptions.items(),
                   key=_by_length if sort_by_length else _by_score),
        )
        parts = ["<ul>"]
        parts.extend([
            f"<li>{description.as_token_string()} ({score:.2})</li>"
            for (description, score) in top_descriptions
        ])
        parts.append("</ul>")
        return "\n".join(parts)
    elif len(descriptions) == 1:
        return "".join(only(descriptions).as_token_string())
    else:
        return ""
コード例 #29
0
    def _decide_primary(self, mo_engagements):
        """Decide which of the engagements in mo_engagements is the primary one.

        Args:
            mo_engagements: List of engagements

        Returns:
            2-tuple:
                UUID: The UUID of the primary engagement.
                primary_type_key: The type of the primary.
        """
        # First we attempt to find a fixed primary engagement.
        # If multiple are found, we throw an exception, as only one is allowed.
        # If one is found, it is our primary and we are done.
        # If none are found, we need to calculate the primary engagement.
        find_fixed_primary = partial(self._predicate_primary_is, "fixed_primary")

        # Iterator of UUIDs of engagements with primary = fixed_primary
        fixed_primary_engagement_uuids = map(
            itemgetter("uuid"), filter(find_fixed_primary, mo_engagements)
        )
        # UUID of engagement with primary = fixed_primary, exception or None
        fixed = only(
            fixed_primary_engagement_uuids, None, too_long=MultipleFixedPrimaries
        )
        if fixed:
            return fixed, "fixed_primary"

        # No fixed engagements, thus we must calculate the primary engagement.
        #
        # The calulcation of primary engagement depends on the underlying
        # implementation, thus we simply call self._find_primary here.
        primary = self._find_primary(mo_engagements)
        if primary:
            return primary, "primary"
        raise NoPrimaryFound()
コード例 #30
0
def split(group):
    name, classes = group
    classes = list(classes)
    no_scope, scope = partition(lambda x: x["name"] != x["user_key"], classes)
    return only(no_scope), only(scope)