예제 #1
0
 def update(self,
            local_address: typing.Optional[Address] = None,
            int_address: typing.Optional[Address] = None,
            phone: typing.Optional[Phone] = None,
            fax: typing.Optional[Phone] = None,
            email: typing.Optional[str] = None,
            entity_type: typing.Optional[int] = None,
            trading_name: typing.Optional[str] = None,
            company_number: typing.Optional[str] = None,
            auth_info: typing.Optional[str] = None) -> bool:
     resp = self._app.stub.ContactUpdate(
         contact_pb2.ContactUpdateRequest(
             id=self.id,
             new_local_address=local_address.to_pb()
             if local_address else None,
             new_internationalised_address=int_address.to_pb()
             if int_address else None,
             new_phone=phone.to_pb() if phone else None,
             new_fax=fax.to_pb() if fax else None,
             new_email=StringValue(
                 value=email) if email and email != self.email else None,
             new_entity_type=entity_type
             if entity_type and entity_type != self.entity_type else None,
             new_trading_name=StringValue(value=trading_name) if
             trading_name and trading_name != self.trading_name else None,
             new_company_number=StringValue(
                 value=company_number) if company_number
             and company_number != self.company_number else None,
             new_auth_info=StringValue(value=auth_info)
             if auth_info and auth_info != self.auth_info else None,
             registry_name=self.registry_name))
     return resp.pending
예제 #2
0
    def scan(
            self,
            table_name: str,
            table_namespace: str = "default",
            start_row: Optional[str] = None,
            stop_row: Optional[str] = None,
            prefix: Optional[str] = None,
            columns: Optional[Mapping[str, List[str]]] = None,
            min_time: Optional[int] = None,
            max_time: Optional[int] = None,
            max_versions: Optional[int] = None
    ) -> Iterator[Result]:

        if start_row is not None:
            _start_row = StringValue(value=start_row)
        else:
            _start_row = None

        if stop_row is not None:
            _stop_row = StringValue(value=stop_row)
        else:
            _stop_row = None

        if prefix is not None:
            _prefix = StringValue(value=prefix)
        else:
            _prefix = None

        if min_time is not None:
            _min_time = Int64Value(value=min_time)
        else:
            _min_time = None

        if max_time is not None:
            _max_time = Int64Value(value=max_time)
        else:
            _max_time = None

        if columns is not None:
            _columns = self._convert_columns(columns)
        else:
            _columns = []

        if max_versions is not None:
            _max_versions = Int32Value(value=max_versions)
        else:
            _max_versions = None

        query = ScanRequest(
            table=Table(name=table_name, namespace=table_namespace),
            start_row=_start_row,
            stop_row=_stop_row,
            prefix=_prefix,
            columns=_columns,
            min_time=_min_time,
            max_time=_max_time,
            max_versions=_max_versions
        )

        return self._client.Scan(query)
예제 #3
0
 def create_contact(
     self,
     contact_id: str,
     local_address: Address,
     int_address: typing.Optional[Address],
     phone: typing.Optional[Phone],
     fax: typing.Optional[Phone],
     email: str,
     entity_type: int,
     trading_name: typing.Optional[str],
     company_number: typing.Optional[str],
     auth_info: str,
     registry_name: str,
 ) -> typing.Tuple[str, bool, datetime.datetime]:
     resp = self.stub.ContactCreate(
         contact_pb2.ContactCreateRequest(
             id=contact_id,
             local_address=local_address.to_pb() if local_address else None,
             internationalised_address=int_address.to_pb()
             if int_address else None,
             phone=phone.to_pb() if phone else None,
             fax=fax.to_pb() if fax else None,
             email=email,
             entity_type=entity_type,
             trading_name=StringValue(
                 value=trading_name) if trading_name else None,
             company_number=StringValue(
                 value=company_number) if company_number else None,
             auth_info=auth_info,
             registry_name=registry_name))
     return resp.id, resp.pending, resp.creation_date.ToDatetime()
    def test_multiple_positions(self):
        sample_sheet = load_sample_sheet_csv(
            sample_sheet_csv_path("good", "multiple_positions"))

        self.compare_sample_sheet(
            sample_sheet,
            [
                ParsedSampleSheetEntry(
                    flow_cell_id=None,
                    position_id="A1",
                    protocol_run_user_info=ProtocolRunUserInfo(
                        sample_id=StringValue(value="my_sample_1"),
                        protocol_group_id=StringValue(value="my_experiment"),
                        barcode_user_info=[
                            BarcodeUserData(barcode_name="barcode01",
                                            alias="alias01"),
                        ],
                    ),
                ),
                ParsedSampleSheetEntry(
                    flow_cell_id=None,
                    position_id="A2",
                    protocol_run_user_info=ProtocolRunUserInfo(
                        sample_id=StringValue(value="my_sample_2"),
                        protocol_group_id=StringValue(value="my_experiment"),
                        barcode_user_info=[
                            BarcodeUserData(barcode_name="barcode01",
                                            alias="alias01"),
                        ],
                    ),
                ),
            ],
        )
예제 #5
0
 def _make_run_userinfo(self, experiment_group_id: str, sample_id: str):
     experiment_group_value = StringValue(value=experiment_group_id)
     sample_id_value = StringValue(value=sample_id)
     protocol_user_info = protocol.ProtocolRunUserInfo(
         protocol_group_id=experiment_group_value,
         sample_id=sample_id_value)
     return protocol_user_info
예제 #6
0
파일: crypto.py 프로젝트: woky/pyrchain
def gen_block_hash_from_block(block: BlockMessage) -> bytes:
    signed_obj = b''.join([
        block.header.SerializeToString(), block.sender,
        StringValue(value=block.sigAlgorithm).SerializeToString(),
        Int32Value(value=block.seqNum).SerializeToString(),
        StringValue(value=block.shardId).SerializeToString(), block.extraBytes
    ])
    return blake2b_32(signed_obj).digest()
예제 #7
0
 def to_api(self) -> messaging_pb2.WebpageMedia:
     if self.image is not None:
         image = self.image.to_api()
     else:
         image = None
     return messaging_pb2.WebpageMedia(
         url=StringValue(value=self.url),
         title=StringValue(value=self.title),
         description=StringValue(value=self.description),
         image=image)
예제 #8
0
def test_nested_deserialization():
    child = Child(name='child', label=StringValue(value='small'))
    parent = Parent(name='parent', label=StringValue(value='big'), child=child)

    data = protobuf_to_dict(parent)
    assert data == dict(name='parent',
                        label='big',
                        child=dict(
                            name='child',
                            label='small',
                            category=None,
                        ))
예제 #9
0
    def scan(self,
             table_name: str,
             table_namespace: str = "default",
             start_row: Optional[str] = None,
             stop_row: Optional[str] = None,
             prefix: Optional[str] = None,
             columns: Mapping[str, List[str]] = None,
             min_time: Optional[int] = None,
             max_time: Optional[int] = None,
             max_versions: Optional[int] = None) -> 'Result':

        if start_row is not None:
            _start_row = StringValue(value=start_row)
        else:
            _start_row = None

        if stop_row is not None:
            _stop_row = StringValue(value=stop_row)
        else:
            _stop_row = None

        if prefix is not None:
            _prefix = StringValue(value=prefix)
        else:
            _prefix = None

        if min_time is not None:
            _min_time = Int64Value(value=min_time)
        else:
            _min_time = None

        if max_time is not None:
            _max_time = Int64Value(value=max_time)
        else:
            _max_time = None

        if max_versions is not None:
            _max_versions = Int32Value(value=max_versions)
        else:
            _max_versions = None

        query = Scan(
            table=Table(name=table_name, namespace=table_namespace),
            start_row=_start_row,
            stop_row=_stop_row,
            prefix=_prefix,
            columns={f: Columns(columns=c)
                     for f, c in columns.items()},
            min_time=_min_time,
            max_time=_max_time,
            max_versions=_max_versions)

        return Result(self._client.scan(query))
def create_calendar(stub: GoogleCalendarServiceStub, user_id: str,
                    summary: str, **kwargs):
    query = GoogleCalendar.Query.Create(
        user_id=user_id,
        calendar=GoogleCalendar(
            summary=StringValue(value=summary),
            description=StringValue(value=kwargs.get('description'))
            if kwargs.get('description') else None,
            location=StringValue(value=kwargs.get('location'))
            if kwargs.get('location') else None,
            timezone=StringValue(value=kwargs.get('timezone'))
            if kwargs.get('timezone') else None))
    result = stub.CreateGoogleCalendar(query)

    return result
def create_event(stub: GoogleCalendarServiceStub, user_id: str,
                 calendar_id: str, summary: str, start: datetime,
                 end: datetime, **kwargs):
    query = GoogleCalendarEvent.Query.Create(
        user_id=user_id,
        calendar_id=calendar_id,
        event=GoogleCalendarEvent(
            summary=StringValue(value=summary),
            start=datetime_to_protobuf(start),
            end=datetime_to_protobuf(end),
            description=StringValue(value=kwargs.get('description'))
            if kwargs.get('description') else None,
            location=StringValue(value=kwargs.get('location'))
            if kwargs.get('location') else None))
    result = stub.CreateGoogleCalendarEvent(query)
    return result
예제 #12
0
    def given_single_step_cbsd_provisioned(self,
                                           builder: CbsdAPIDataBuilder) -> int:
        self.when_cbsd_is_created(builder.payload)
        update_request = EnodebdUpdateCbsdRequest(
            serial_number=self.serial_number,
            installation_param=InstallationParam(
                antenna_gain=DoubleValue(value=15),
                latitude_deg=DoubleValue(value=10.5),
                longitude_deg=DoubleValue(value=11.5),
                indoor_deployment=BoolValue(value=True),
                height_type=StringValue(value="agl"),
                height_m=DoubleValue(value=12.5),
            ),
            cbsd_category="a",
        )
        self.when_cbsd_is_updated_by_enodebd(update_request)
        cbsd = self.when_cbsd_is_fetched(builder.payload["serial_number"])
        self.then_cbsd_is(
            cbsd,
            builder.with_state(UNREGISTERED).with_is_active(False).
            with_full_installation_param().with_cbsd_category("a").payload,
        )

        state = self.when_cbsd_asks_for_state()
        self.then_state_is(state, get_empty_state())

        cbsd = self._check_cbsd_successfully_provisioned(builder)

        return cbsd['id']
예제 #13
0
    def test_cbsd_not_unregistered_when_coordinates_change_less_than_10_m(
            self):
        builder = CbsdAPIDataBuilder()\
            .with_single_step_enabled(True) \
            .with_capabilities() \
            .with_frequency_preferences() \
            .with_desired_state() \
            .with_serial_number(self.serial_number) \
            .with_full_installation_param() \
            .with_cbsd_category("a")

        self.given_single_step_cbsd_provisioned(builder)
        with self.while_cbsd_is_active():
            filters = get_filters_for_request_type('deregistration',
                                                   self.serial_number)

            update_request = EnodebdUpdateCbsdRequest(
                serial_number=self.serial_number,
                installation_param=InstallationParam(
                    antenna_gain=DoubleValue(value=15),
                    latitude_deg=DoubleValue(value=10.500001),
                    longitude_deg=DoubleValue(value=11.5000001),
                    indoor_deployment=BoolValue(value=True),
                    height_type=StringValue(value="agl"),
                    height_m=DoubleValue(value=12.5),
                ),
                cbsd_category="a",
            )

            self.when_cbsd_is_updated_by_enodebd(update_request)
            cbsd = self.when_cbsd_is_fetched(self.serial_number)
            self.then_cbsd_is(cbsd, builder.payload)
            self.then_message_is_never_sent(filters)
예제 #14
0
 def transfer_query_domain(self, domain: str, auth_info: typing.Optional[str] = None) -> \
         DomainTransfer:
     resp = self.stub.DomainTransferQuery(
         domain_pb2.DomainTransferQueryRequest(
             name=domain,
             auth_info=StringValue(value=auth_info) if auth_info else None))
     return DomainTransfer.from_pb(resp)
 def test_no_barcoding(self):
     sample_sheet = load_sample_sheet_csv(
         sample_sheet_csv_path("good", "no_barcoding"))
     self.compare_sample_sheet(
         sample_sheet,
         [
             ParsedSampleSheetEntry(
                 flow_cell_id="FC001",
                 position_id=None,
                 protocol_run_user_info=ProtocolRunUserInfo(
                     sample_id=StringValue(value="my_sample"),
                     protocol_group_id=StringValue(value="my_experiment"),
                 ),
             ),
         ],
     )
예제 #16
0
파일: dp_client.py 프로젝트: rsarwad/magma
def build_enodebd_update_cbsd_request(
    serial_number: str,
    latitude_deg: str,
    longitude_deg: str,
    indoor_deployment: str,
    antenna_height: str,
    antenna_height_type: str,
    cbsd_category: str,
) -> EnodebdUpdateCbsdRequest:
    # cbsd category and antenna height type should be converted to lowercase
    # for the gRPC call
    antenna_height_type = antenna_height_type.lower()
    cbsd_category = cbsd_category.lower()
    # lat and long values are part of tr181 specification, but they are kept in device config
    # transformed and eventually kept within the device config as strings representing degrees
    latitude_deg_float = float(latitude_deg)
    longitude_deg_float = float(longitude_deg)

    indoor_deployment_bool = _indoortobool(indoor_deployment)
    antenna_height_float = float(antenna_height)

    installation_param = InstallationParam(
        latitude_deg=DoubleValue(value=latitude_deg_float),
        longitude_deg=DoubleValue(value=longitude_deg_float),
        indoor_deployment=BoolValue(value=indoor_deployment_bool),
        height_m=DoubleValue(value=antenna_height_float),
        height_type=StringValue(value=antenna_height_type),
    )

    return EnodebdUpdateCbsdRequest(
        serial_number=serial_number,
        installation_param=installation_param,
        cbsd_category=cbsd_category,
    )
 def set_proto(self, response_object):
     response_object.error.code = self.code
     response_object.error.message = str(self)
     response_object.error.status_code = self.status_code
     if self.client_minimum_version:
         response_object.error.minimumVersion.CopyFrom(
             StringValue(value=self.client_minimum_version))
예제 #18
0
 def test_call_metrics(self):
     servicer = MagicMock(test_service_pb2_grpc.TestServiceServicer)
     servicer.UnaryUnary = lambda x, _: x
     with inprocess_grpc_server(
             servicer, test_service_pb2_grpc.
             add_TestServiceServicer_to_server) as address:
         set_global_tracer(global_tracer())
         client = make_grpc_client("foo", "bar", address,
                                   test_service_pb2_grpc.TestServiceStub)
         unary_value = StringValue(value="foo")
         self.assertEqual(unary_value, client.UnaryUnary(unary_value))
         labels = {
             "client_name": "foo",
             "server_name": "bar",
             "service": "eagr_TestService",
             "endpoint": "UnaryUnary",
         }
         call_count = REGISTRY.get_sample_value(
             "clientside_grpc_endpoint_count", labels=labels)
         self.assertEqual(1, call_count)
         # Try that again to see if the number changes
         self.assertEqual(unary_value, client.UnaryUnary(unary_value))
         call_count = REGISTRY.get_sample_value(
             "clientside_grpc_endpoint_count", labels=labels)
         self.assertEqual(2, call_count)
예제 #19
0
    def test_exception_tracking(self):
        servicer = MagicMock(test_service_pb2_grpc.TestServiceServicer)
        servicer.UnaryUnary = lambda x, _: time.sleep(10)
        count_labels = {
            "client_name": "foo",
            "server_name": "bar",
            "service": "eagr_TestService",
            "endpoint": "UnaryUnary",
        }
        exception_labels = dict(count_labels, exception="TimeoutError")

        with inprocess_grpc_server(
                servicer, test_service_pb2_grpc.
                add_TestServiceServicer_to_server) as address:
            set_global_tracer(global_tracer())
            client = make_grpc_client("foo", "bar", address,
                                      test_service_pb2_grpc.TestServiceStub)
            calls_before = (REGISTRY.get_sample_value(
                "clientside_grpc_endpoint_count", labels=count_labels) or 0)
            exceptions_before = (REGISTRY.get_sample_value(
                "clientside_grpc_endpoint_error_total",
                labels=exception_labels) or 0)
            with self.assertRaises(TimeoutError):
                client.UnaryUnary(StringValue(value="foo"), timeout=1)
            calls_after = REGISTRY.get_sample_value(
                "clientside_grpc_endpoint_count", labels=count_labels)
            exceptions_after = REGISTRY.get_sample_value(
                "clientside_grpc_endpoint_error_total",
                labels=exception_labels)

            self.assertEqual(1, calls_after - calls_before)
            print(exceptions_after, exceptions_before)  # noqa
            self.assertEqual(1, exceptions_after - exceptions_before)
예제 #20
0
    def edit_nickname(self, nick: str) -> None:
        """Edit bot nickname (shortname).

        :param nick: new bot nickname.
        :return: None
        """
        self.internal.profile.EditNickName(profile_pb2.RequestEditNickName(nickname=StringValue(value=nick)))
예제 #21
0
    def edit_about(self, about: str) -> None:
        """Edit bot about.

        :param about: new bot about.
        :return:
        """
        self.internal.profile.EditAbout(profile_pb2.RequestEditAbout(about=StringValue(value=about)))
예제 #22
0
    def get_observation(self, obs_id):
        respond = self.stub.getObservation(StringValue(value=obs_id))
        observation = []
        for obs in respond.obs:
            observation.append(obs)

        return observation
예제 #23
0
    def get_formatted_address(self, address):
        """
        Get formatted address
        :param address: address
        :return: the formatted address
        """
        if isinstance(address, Address):
            address = base58.b58encode_check(address.value).decode()

        token_contract_address = self.get_system_contract_address('AElf.ContractNames.Token')
        transaction = self.create_transaction(token_contract_address, 'GetPrimaryTokenSymbol')
        transaction = self.sign_transaction(self._private_key, transaction)
        raw_symbol = self.execute_transaction(transaction)
        symbol = StringValue()
        symbol.ParseFromString(bytes.fromhex(raw_symbol.decode()))

        chain_status = self.get_chain_status()
        return '%s_%s_%s' % (symbol.value, address, chain_status['ChainId'])
예제 #24
0
    def edit_user_status(self, type: UserStatus, text: str) -> None:
        """Edit bot sex.

        :param type: new bot status type.
        :param text: new bot status text.
        :return: None.
        """
        self.internal.profile.ChangeUserStatus(
            profile_pb2.RequestChangeUserStatus(status=users_pb2.UserStatus(
                type=type, text=StringValue(value=text))))
 def PeerSearch(self, request: RequestPeerSearch) -> ResponsePeerSearch:
     return ResponsePeerSearch(
         users=[],
         groups=[],
         search_results=[
             PeerSearchResult(peer=Peer(id=1, type=PEERTYPE_GROUP),
                              shortname=StringValue(value="short_name"))
         ],
         user_peers=[],
         group_peers=[])
예제 #26
0
 def upload_animated_move_async(self, animation, generated_id="", **kwargs):
     """Async version of upload_animated_move()."""
     gen_id_proto = StringValue(value=generated_id)
     req = choreography_sequence_pb2.UploadAnimatedMoveRequest(
         animated_move=animation, animated_move_generated_id=gen_id_proto)
     return self.call_async(
         self._stub.UploadAnimatedMove,
         req,
         value_from_response=None,  # Return the complete response message
         error_from_response=_upload_animated_move_errors,
         **kwargs)
def update_event(stub: GoogleCalendarServiceStub, user_id: str,
                 calendar_id: str, event_id: str, **kwargs):
    query = GoogleCalendarEvent.Query.Update(
        user_id=user_id,
        calendar_id=calendar_id,
        event_id=event_id,
        event=GoogleCalendarEvent(
            summary=StringValue(value=kwargs.get('summary'))
            if kwargs.get('summary') else None,
            start=datetime_to_protobuf(kwargs.get('start'))
            if kwargs.get('start') and type(kwargs.get('start')) is datetime
            else None,
            end=datetime_to_protobuf(kwargs.get('end')) if kwargs.get('end')
            and type(kwargs.get('end')) is datetime else None,
            description=StringValue(value=kwargs.get('description'))
            if kwargs.get('description') else None,
            location=StringValue(value=kwargs.get('location'))
            if kwargs.get('location') else None))
    result = stub.UpdateGoogleCalendarEvent(query)
    return result
예제 #28
0
    def test_methods(self):
        with inprocess_grpc_server(
            Servicer(), test_service_pb2_grpc.add_TestServiceServicer_to_server
        ) as address:
            channel = grpc.insecure_channel(address)
            stub = test_service_pb2_grpc.TestServiceStub(channel)

            unary_value = StringValue(value="foo")
            self.assertEqual(unary_value, stub.UnaryUnary(unary_value))
            self.assertEqual([unary_value] * 10, list(stub.UnaryStream(unary_value)))

            data_to_stream = [
                StringValue(value="foo"),
                StringValue(value="bar"),
                StringValue(value="baz"),
            ]

            self.assertEqual(
                StringValue(value="foobarbaz"), stub.StreamUnary((x for x in data_to_stream))
            )
            self.assertEqual(data_to_stream, list(stub.StreamStream((x for x in data_to_stream))))
    async def _save_result(self, group, task_id, proto, task_results, size_of_state):
        saved_to_storage = False

        if self._storage is not None and size_of_state >= self._storage.threshold:
            saved_to_storage = await self._try_save_to_store([group.group_id, task_id], proto)

        if saved_to_storage: 
            # record ptr to state
            task_results.by_id[task_id].CopyFrom(pack_any(StringValue(value=task_id)))
        else:
            # record data to state
            task_results.by_id[task_id].CopyFrom(proto)
예제 #30
0
 def to_pb(self) -> contact_pb2.PostalAddress:
     if self.birth_date:
         birth_date = Timestamp()
         birth_date.FromDatetime(
             datetime.datetime.combine(self.birth_date,
                                       datetime.datetime.min.time()))
     else:
         birth_date = None
     return contact_pb2.PostalAddress(
         name=self.name,
         organisation=StringValue(
             value=self.organisation) if self.organisation else None,
         streets=self.streets,
         city=self.city,
         province=StringValue(
             value=self.province) if self.province else None,
         postal_code=StringValue(
             value=self.postal_code) if self.postal_code else None,
         country_code=self.country_code,
         identity_number=StringValue(
             value=self.identity_number) if self.identity_number else None,
         birth_date=birth_date)