Python types.LambdaType() Examples

The following are 30 code examples for showing how to use types.LambdaType(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module types , or try the search function .

Example 1
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 6 votes vote down vote up
def _get_calculated_size(self, size, data):
        """
        Get's the final size of the field and runs the lambda functions
        recursively until a final size is derived. If size is None then it
        will just return the length of the data as it is assumed it is the
        final field (None should only be set on size for the final field).

        :param size: The size to calculate/expand
        :param data: The data that the size is being calculated for
        :return: The final size
        """
        # if the size is derived from a lambda function, run it now; otherwise
        # return the value we passed in or the length of the data if the size
        # is None (last field value)
        if size is None:
            return len(data)
        elif isinstance(size, types.LambdaType):
            expanded_size = size(self.structure)
            return self._get_calculated_size(expanded_size, data)
        else:
            return size 
Example 2
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 6 votes vote down vote up
def _parse_value(self, value):
        if value is None:
            int_value = 0
        elif isinstance(value, types.LambdaType):
            int_value = value
        elif isinstance(value, bytes):
            format = self._get_struct_format(self.size, self.unsigned)
            struct_string = "%s%s"\
                            % ("<" if self.little_endian else ">", format)
            int_value = struct.unpack(struct_string, value)[0]
        elif isinstance(value, integer_types):
            int_value = value
        else:
            raise TypeError("Cannot parse value for field %s of type %s to "
                            "an int" % (self.name, type(value).__name__))
        return int_value 
Example 3
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 6 votes vote down vote up
def _parse_value(self, value):
        if value is None:
            bytes_value = b""
        elif isinstance(value, types.LambdaType):
            bytes_value = value
        elif isinstance(value, integer_types):
            format = self._get_struct_format(self.size)
            struct_string = "%s%s"\
                            % ("<" if self.little_endian else ">", format)
            bytes_value = struct.pack(struct_string, value)
        elif isinstance(value, Structure):
            bytes_value = value.pack()
        elif isinstance(value, bytes):
            bytes_value = value
        else:
            raise TypeError("Cannot parse value for field %s of type %s to a "
                            "byte string" % (self.name, type(value).__name__))
        return bytes_value 
Example 4
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 6 votes vote down vote up
def _parse_value(self, value):
        if value is None:
            list_value = []
        elif isinstance(value, types.LambdaType):
            return value
        elif isinstance(value, bytes) and isinstance(self.unpack_func,
                                                     types.LambdaType):
            # use the lambda function to parse the bytes to a list
            list_value = self.unpack_func(self.structure, value)
        elif isinstance(value, bytes):
            # we have a fixed length array with a specified count
            list_value = self._create_list_from_bytes(self.list_count,
                                                      self.list_type, value)
        elif isinstance(value, list):
            # manually parse each list entry to the field type specified
            list_value = value
        else:
            raise TypeError("Cannot parse value for field %s of type %s to a "
                            "list" % (self.name, type(value).__name__))
        list_value = [self._parse_sub_value(v) for v in list_value]
        return list_value 
Example 5
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 6 votes vote down vote up
def _parse_value(self, value):
        if value is None:
            structure_value = b""
        elif isinstance(value, types.LambdaType):
            structure_value = value
        elif isinstance(value, bytes):
            structure_value = value
        elif isinstance(value, Structure):
            structure_value = value
        else:
            raise TypeError("Cannot parse value for field %s of type %s to a "
                            "structure" % (self.name, type(value).__name__))

        if isinstance(structure_value, bytes) and self.structure_type and \
                structure_value != b"":
            if isinstance(self.structure_type, types.LambdaType):
                structure_type = self.structure_type(self.structure)
            else:
                structure_type = self.structure_type
            structure = structure_type()
            structure.unpack(structure_value)
            structure_value = structure
        return structure_value 
Example 6
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 6 votes vote down vote up
def _parse_value(self, value):
        if value is None:
            datetime_value = datetime.today()
        elif isinstance(value, types.LambdaType):
            datetime_value = value
        elif isinstance(value, bytes):
            format = self._get_struct_format(8)
            struct_string = "%s%s"\
                            % ("<" if self.little_endian else ">", format)
            int_value = struct.unpack(struct_string, value)[0]
            return self._parse_value(int_value)  # just parse the value again
        elif isinstance(value, integer_types):

            time_microseconds = (value - self.EPOCH_FILETIME) // 10
            datetime_value = datetime(1970, 1, 1) + \
                timedelta(microseconds=time_microseconds)
        elif isinstance(value, datetime):
            datetime_value = value
        else:
            raise TypeError("Cannot parse value for field %s of type %s to a "
                            "datetime" % (self.name, type(value).__name__))
        return datetime_value 
Example 7
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 6 votes vote down vote up
def _parse_value(self, value):
        if value is None:
            uuid_value = uuid.UUID(bytes=b"\x00" * 16)
        elif isinstance(value, bytes) and self.little_endian:
            uuid_value = uuid.UUID(bytes=value)
        elif isinstance(value, bytes) and not self.little_endian:
            uuid_value = uuid.UUID(bytes_le=value)
        elif isinstance(value, integer_types):
            uuid_value = uuid.UUID(int=value)
        elif isinstance(value, uuid.UUID):
            uuid_value = value
        elif isinstance(value, types.LambdaType):
            uuid_value = value
        else:
            raise TypeError("Cannot parse value for field %s of type %s to a "
                            "uuid" % (self.name, type(value).__name__))
        return uuid_value 
Example 8
Project: ai-platform   Author: produvia   File: run_context.py    License: MIT License 6 votes vote down vote up
def __init__(self, submit_config: submit.SubmitConfig, config_module: types.ModuleType = None, max_epoch: Any = None):
        self.submit_config = submit_config
        self.should_stop_flag = False
        self.has_closed = False
        self.start_time = time.time()
        self.last_update_time = time.time()
        self.last_update_interval = 0.0
        self.max_epoch = max_epoch

        # pretty print the all the relevant content of the config module to a text file
        if config_module is not None:
            with open(os.path.join(submit_config.run_dir, "config.txt"), "w") as f:
                filtered_dict = {k: v for k, v in config_module.__dict__.items() if not k.startswith("_") and not isinstance(v, (types.ModuleType, types.FunctionType, types.LambdaType, submit.SubmitConfig, type))}
                pprint.pprint(filtered_dict, stream=f, indent=4, width=200, compact=False)

        # write out details about the run to a text file
        self.run_txt_data = {"task_name": submit_config.task_name, "host_name": submit_config.host_name, "start_time": datetime.datetime.now().isoformat(sep=" ")}
        with open(os.path.join(submit_config.run_dir, "run.txt"), "w") as f:
            pprint.pprint(self.run_txt_data, stream=f, indent=4, width=200, compact=False) 
Example 9
Project: rasa_wechat   Author: Rowl1ng   File: processor.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 interpreter,  # type: NaturalLanguageInterpreter
                 policy_ensemble,  # type: PolicyEnsemble
                 domain,  # type: Domain
                 tracker_store,  # type: TrackerStore
                 max_number_of_predictions=10,  # type: int
                 message_preprocessor=None,  # type: Optional[LambdaType]
                 on_circuit_break=None  # type: Optional[LambdaType]
                 ):
        self.interpreter = interpreter
        self.policy_ensemble = policy_ensemble
        self.domain = domain
        self.tracker_store = tracker_store
        self.max_number_of_predictions = max_number_of_predictions
        self.message_preprocessor = message_preprocessor
        self.on_circuit_break = on_circuit_break 
Example 10
Project: blitzdb   Author: adewes   File: backend.py    License: MIT License 6 votes vote down vote up
def get_field_type(self,field,name = None):
        m = {
            IntegerField : Integer,
            FloatField : Float,
            CharField : lambda field: String(length = field.length),
            EnumField : lambda field: Enum(*field.enums,name = name,native_enum = field.native_enum),
            TextField : Text,
            BooleanField: Boolean,
            BinaryField: LargeBinary,
            DateField: Date,
            DateTimeField: DateTime
        }
        for cls,t in m.items():
            if isinstance(field,cls):
                if isinstance(t,LambdaType):
                    return t(field)
                return t
        raise AttributeError("Invalid field type: %s" % field) 
Example 11
Project: GraphicDesignPatternByPython   Author: Relph1119   File: core.py    License: MIT License 6 votes vote down vote up
def get_config(self):
        if isinstance(self.function, python_types.LambdaType):
            function = func_dump(self.function)
            function_type = 'lambda'
        else:
            function = self.function.__name__
            function_type = 'function'

        if isinstance(self._output_shape, python_types.LambdaType):
            output_shape = func_dump(self._output_shape)
            output_shape_type = 'lambda'
        elif callable(self._output_shape):
            output_shape = self._output_shape.__name__
            output_shape_type = 'function'
        else:
            output_shape = self._output_shape
            output_shape_type = 'raw'

        config = {'function': function,
                  'function_type': function_type,
                  'output_shape': output_shape,
                  'output_shape_type': output_shape_type,
                  'arguments': self.arguments}
        base_config = super(Lambda, self).get_config()
        return dict(list(base_config.items()) + list(config.items())) 
Example 12
Project: rasa_core   Author: RasaHQ   File: processor.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 interpreter: NaturalLanguageInterpreter,
                 policy_ensemble: PolicyEnsemble,
                 domain: Domain,
                 tracker_store: TrackerStore,
                 generator: NaturalLanguageGenerator,
                 action_endpoint: Optional[EndpointConfig] = None,
                 max_number_of_predictions: int = 10,
                 message_preprocessor: Optional[LambdaType] = None,
                 on_circuit_break: Optional[LambdaType] = None,
                 ):
        self.interpreter = interpreter
        self.nlg = generator
        self.policy_ensemble = policy_ensemble
        self.domain = domain
        self.tracker_store = tracker_store
        self.max_number_of_predictions = max_number_of_predictions
        self.message_preprocessor = message_preprocessor
        self.on_circuit_break = on_circuit_break
        self.action_endpoint = action_endpoint 
Example 13
Project: code   Author: ActiveState   File: recipe-473818.py    License: MIT License 6 votes vote down vote up
def new_looper(a, arg=None):
    """Helper function for nest()
    determines what sort of looper to make given a's type"""
    if isinstance(a,types.TupleType):
        if len(a) == 2:
            return RangeLooper(a[0],a[1])
        elif len(a) == 3:
            return RangeLooper(a[0],a[1],a[2])
    elif isinstance(a, types.BooleanType):
        return BooleanLooper(a)
    elif isinstance(a,types.IntType) or isinstance(a, types.LongType):
        return RangeLooper(a)
    elif isinstance(a, types.StringType) or isinstance(a, types.ListType):
        return ListLooper(a)
    elif isinstance(a, Looper):
        return a
    elif isinstance(a, types.LambdaType):
        return CalcField(a, arg) 
Example 14
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: 4567)
        expected = 4567
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual == expected
        assert len(field) == 4 
Example 15
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: b"\x10\x11\x12\x13")
        expected = b"\x10\x11\x12\x13"
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual == expected
        assert len(field) == 4 
Example 16
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda_as_bytes(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: b"\x10\x11\x12\x13")
        expected = [b"\x10\x11", b"\x12\x13"]
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual == expected
        assert len(field) == 4 
Example 17
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda_as_list(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: [b"\x10\x11", b"\x12\x13"])
        expected = [b"\x10\x11", b"\x12\x13"]
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual == expected
        assert len(field) == 4 
Example 18
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: b"\x7d\x00\x00\x00\x14\x15\x16\x17")
        expected = b"\x7d\x00\x00\x00\x14\x15\x16\x17"
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual.pack() == expected
        assert isinstance(actual, Structure2)
        assert len(field) == 8 
Example 19
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: uuid.UUID(bytes=b"\x11" * 16))
        expected = uuid.UUID(bytes=b"\x11" * 16)
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual == expected
        assert len(field) == 16 
Example 20
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: datetime(year=1960, month=8, day=2, hour=8,
                                           minute=7, second=1,
                                           microsecond=186774))
        expected = datetime(year=1960, month=8, day=2, hour=8, minute=7,
                            second=1, microsecond=186774)
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual == expected
        assert len(field) == 8 
Example 21
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: True)
        expected = True
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual == expected
        assert len(field) == 1 
Example 22
Project: smbprotocol   Author: jborean93   File: test_structure.py    License: MIT License 5 votes vote down vote up
def test_set_lambda(self):
        structure = self.StructureTest()
        field = structure['field']
        field.name = "field"
        field.structure = self.StructureTest
        field.set_value(lambda s: self.STRING_VALUE)
        expected = self.STRING_VALUE
        actual = field.get_value()
        assert isinstance(field.value, types.LambdaType)
        assert actual == expected
        assert len(field) == 19 
Example 23
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 5 votes vote down vote up
def __init__(self, little_endian=True, default=None, size=None):
        """
        The base class of a Field object. This contains the framework that a
        field SHOULD implement in regards to packing and unpacking a value.
        There should be little need to call this particular object as it is
        designed to be a base class for *Type classes.

        :param little_endian: When converting an int/uuid to bytes, the byte
            order to pack as, False means it will be big endian
        :param default: The default value of the field, this can be any
            supported value such as as well as a lambda function or None
            (default).
        :param size: The size of the field, this can be an int, lambda function
            or None (for variable length end field) unless overridden in Class
            definition.
        """
        field_type = self.__class__.__name__
        self.little_endian = little_endian

        if not (size is None or isinstance(size, integer_types) or
                isinstance(size, types.LambdaType)):
            raise InvalidFieldDefinition("%s size for field must be an int or "
                                         "None for a variable length"
                                         % field_type)
        self.size = size
        self.default = default
        self.value = None 
Example 24
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 5 votes vote down vote up
def _get_struct_format(self, size, unsigned=True):
        """
        Get's the format specified for use in struct. This is only designed
        for 1, 2, 4, or 8 byte values and will throw an exception if it is
        anything else.

        :param size: The size as an int
        :return: The struct format specifier for the size specified
        """
        if isinstance(size, types.LambdaType):
            size = size(self.structure)

        struct_format = {
            1: 'B',
            2: 'H',
            4: 'L',
            8: 'Q'
        }
        if size not in struct_format.keys():
            raise InvalidFieldDefinition("Cannot struct format of size %s"
                                         % size)
        format_char = struct_format[size]
        if not unsigned:
            format_char = format_char.lower()

        return format_char 
Example 25
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 5 votes vote down vote up
def _create_list_from_bytes(self, list_count, list_type, value):
        # calculate the list_count and rerun method if a lambda
        if isinstance(list_count, types.LambdaType):
            list_count = list_count(self.structure)
            return self._create_list_from_bytes(list_count, list_type, value)

        list_value = []
        for idx in range(0, list_count):
            new_field = copy.deepcopy(list_type)
            value = new_field.unpack(value)
            list_value.append(new_field)
        return list_value 
Example 26
Project: smbprotocol   Author: jborean93   File: structure.py    License: MIT License 5 votes vote down vote up
def _parse_value(self, value):
        if value is None:
            text_value = u""
        elif isinstance(value, binary_type):
            text_value = to_text(value, encoding=self.encoding)
        elif isinstance(value, text_type):
            text_value = value
        elif isinstance(value, types.LambdaType):
            text_value = value
        else:
            raise TypeError("Cannot parse value for field %s of type %s to a "
                            "text string" % (self.name, type(value).__name__))

        return text_value 
Example 27
Project: ACAN   Author: miraiaroha   File: transforms.py    License: MIT License 5 votes vote down vote up
def __init__(self, lambd):
        assert isinstance(lambd, types.LambdaType)
        self.lambd = lambd 
Example 28
Project: DeepLung   Author: uci-cbcl   File: transforms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, lambd):
        assert isinstance(lambd, types.LambdaType)
        self.lambd = lambd 
Example 29
Project: CSD-SSD   Author: soo89   File: augmentations.py    License: MIT License 5 votes vote down vote up
def __init__(self, lambd):
        assert isinstance(lambd, types.LambdaType)
        self.lambd = lambd 
Example 30
Project: neat-python   Author: CodeReclaimers   File: aggregations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_aggregation(function):  # TODO: Recognize when need `reduce`
    if not isinstance(function,
                      (types.BuiltinFunctionType,
                       types.FunctionType,
                       types.LambdaType)):
        raise InvalidAggregationFunction("A function object is required.")

    if not (function.__code__.co_argcount >= 1):
        raise InvalidAggregationFunction("A function taking at least one argument is required")