Python Code Examples for enum

60 Python code examples are found related to "enum". 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.
Example 1
Project: gxpy   Author: GeosoftInc   File: GXMETA.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def set_attrib_enum(self, ph_object, ph_attrib, value):
        """
        Set an enum value to an attribute (as an integer)
        
        :param ph_object:  Object
        :param ph_attrib:  Attribute
        :param value:      Value to set
        :type  ph_object:  int
        :type  ph_attrib:  int
        :type  value:      int

        .. versionadded:: 5.1.6

        **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_
        """
        self._set_attrib_enum(ph_object, ph_attrib, value) 
Example 2
Project: public_tools   Author: pan-unit42   File: deobfuscate_api_calls.py    License: MIT License 6 votes vote down vote up
def get_all_enum_constants():
	'''
	Returns hash of constant numerical representations. Value of each key is an 
	array containing the constant name (array[0]) and the constant ID (array[1]).
	'''
	constants = {}
	all_enums = GetEnumQty()
	for i in range(0, all_enums):
		en = GetnEnum(i)
		first = GetFirstConst(en, -1)
		v1 = GetConstEx(en, first, 0, -1)
		name = GetConstName(v1)
		constants[int(first)] = [name, en]
		while True:
			first = GetNextConst(en, first, -1)
			v1 = GetConstEx(en, first, 0, -1)
			name = GetConstName(v1)
			if first == 0xFFFFFFFF:
				break
			constants[int(first)] = [name, en]
	return constants


# Grabbing all enumerations in the IDB and storing to a variable for later use. 
Example 3
Project: data_pipeline_avro_util   Author: Yelp   File: avro_builder.py    License: Apache License 2.0 6 votes vote down vote up
def begin_enum(self, name, symbols, namespace=None, aliases=None,
                   doc=None, **metadata):
        enum_schema = {
            'type': 'enum',
            'name': name,
            'symbols': symbols
        }
        if namespace:
            self._set_namespace(enum_schema, namespace)
        if aliases:
            self._set_aliases(enum_schema, aliases)
        if doc:
            self._set_doc(enum_schema, doc)
        enum_schema.update(metadata)

        self._save_current_schema()
        self._set_current_schema(enum_schema)
        return self 
Example 4
Project: OpenXR-SDK-Source   Author: KhronosGroup   File: entity_db.py    License: Apache License 2.0 6 votes vote down vote up
def handleEnumValue(self, name, info):
        """Add entities, if appropriate, for an item in registry.enumdict.

        Called at construction for every name, info in registry.enumdict.items().
        Calls self.addEntity() accordingly.
        """
        self.addEntity(name, 'ename', elem=info.elem,
                       category='enumvalues', generates=False)

    ###
    # END of methods intended to be implemented, overridden, or extended in child classes!
    ###

    ###
    # Accessors
    ### 
Example 5
Project: abseil-py   Author: abseil   File: _defines.py    License: Apache License 2.0 6 votes vote down vote up
def DEFINE_enum_class(  # pylint: disable=invalid-name,redefined-builtin
    name, default, enum_class, help, flag_values=_flagvalues.FLAGS,
    module_name=None, **args):
  """Registers a flag whose value can be the name of enum members.

  Args:
    name: str, the flag name.
    default: Enum|str|None, the default value of the flag.
    enum_class: class, the Enum class with all the possible values for the flag.
    help: str, the help message.
    flag_values: FlagValues, the FlagValues instance with which the flag will
        be registered. This should almost never need to be overridden.
    module_name: str, the name of the Python module declaring this flag.
        If not provided, it will be computed using the stack trace of this call.
    **args: dict, the extra keyword args that are passed to Flag __init__.
  """
  DEFINE_flag(_flag.EnumClassFlag(name, default, help, enum_class, **args),
              flag_values, module_name) 
Example 6
Project: graphene-django   Author: graphql-python   File: converter.py    License: MIT License 6 votes vote down vote up
def generate_enum_name(django_model_meta, field):
    if graphene_settings.DJANGO_CHOICE_FIELD_ENUM_CUSTOM_NAME:
        # Try and import custom function
        custom_func = import_string(
            graphene_settings.DJANGO_CHOICE_FIELD_ENUM_CUSTOM_NAME
        )
        name = custom_func(field)
    elif graphene_settings.DJANGO_CHOICE_FIELD_ENUM_V3_NAMING is True:
        name = "{app_label}{object_name}{field_name}Choices".format(
            app_label=to_camel_case(django_model_meta.app_label.title()),
            object_name=django_model_meta.object_name,
            field_name=to_camel_case(field.name.title()),
        )
    else:
        name = to_camel_case("{}_{}".format(django_model_meta.object_name, field.name))
    return name 
Example 7
Project: graphene-sqlalchemy   Author: graphql-python   File: utils.py    License: MIT License 6 votes vote down vote up
def sort_enum_for_model(cls, name=None, symbol_name=None):
    """Get a Graphene Enum for sorting the given model class.

    This is deprecated, please use object_type.sort_enum() instead.
    """
    warnings.warn(
        "sort_enum_for_model() is deprecated; use object_type.sort_enum() instead.",
        DeprecationWarning,
        stacklevel=2,
    )

    from .enums import sort_enum_for_object_type

    return sort_enum_for_object_type(
        _deprecated_object_type_for_model(cls, name),
        name,
        get_symbol_name=symbol_name or _deprecated_default_symbol_name,
    ) 
Example 8
Project: Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda   Author: PacktPublishing   File: descriptor_pool.py    License: MIT License 6 votes vote down vote up
def FindEnumTypeByName(self, full_name):
    """Loads the named enum descriptor from the pool.

    Args:
      full_name: The full name of the enum descriptor to load.

    Returns:
      The enum descriptor for the named type.

    Raises:
      KeyError: if the enum cannot be found in the pool.
    """

    full_name = _NormalizeFullyQualifiedName(full_name)
    if full_name not in self._enum_descriptors:
      self._FindFileContainingSymbolInDb(full_name)
    return self._enum_descriptors[full_name] 
Example 9
Project: xed   Author: intelxed   File: enum_txt_writer.py    License: Apache License 2.0 6 votes vote down vote up
def print_enum_header(self,fp): # private
        fp.write('namespace %s\n' % self.namespace)
        fp.write('cfn %s\n' % self.cfn)
        fp.write('hfn %s\n' % self.hfn)
        fp.write('typename %s\n' % self.type_name)
        fp.write('prefix %s\n' % self.prefix)
        if self.stream_ifdef and self.stream_ifdef != '':
            fp.write('stream_ifdef %s\n' % self.stream_ifdef)
        if self.cplusplus:
            fp.write("cplusplus\n")
        if self.proto_prefix:
            fp.write("proto_prefix %s\n" % self.proto_prefix)
        if self.extra_header:
            if isinstance(self.extra_header,list):
                for f in self.extra_header:
                    fp.write("extra_header %s\n" % f)
            else:
                fp.write("extra_header %s\n" % self.extra_header) 
Example 10
Project: OpenXR-SDK-Source   Author: KhronosGroup   File: reg.py    License: Apache License 2.0 6 votes vote down vote up
def markEnumRequired(self, enumname, required):
        """Mark an enum as required or not.

        - enumname - name of enum
        - required - boolean (to tag features as required or not)"""
        self.gen.logMsg('diag', 'tagging enum:', enumname, '-> required =', required)
        enum = self.lookupElementInfo(enumname, self.enumdict)
        if enum is not None:
            enum.required = required
            # Tag enum dependencies in 'alias' attribute as required
            depname = enum.elem.get('alias')
            if depname:
                self.gen.logMsg('diag', 'Generating dependent enum',
                                depname, 'for alias', enumname, 'required =', enum.required)
                self.markEnumRequired(depname, required)
        else:
            self.gen.logMsg('warn', 'enum:', enumname, 'IS NOT DEFINED') 
Example 11
Project: surreal   Author: SurrealAI   File: common.py    License: MIT License 6 votes vote down vote up
def get_enum(enum_class, option):
    """
    Args:
        enum_class:
        option: if the value doesn't belong to Enum, throw error.
            Can be either the str name or the actual enum value
    """
    assert issubclass(enum_class, StringEnum)
    if isinstance(option, enum_class):
        return option
    else:
        assert_type(option, str)
        option = option.lower()
        options = enum_class.__members__
        if option not in options:
            raise ValueError('"{}" is not a valid option for {}. '
                             'Available options are {}.'
             .format(option, enum_class.__name__, list(options)))
        return options[option] 
Example 12
Project: dagster   Author: dagster-io   File: dauphin_registry.py    License: Apache License 2.0 6 votes vote down vote up
def create_enum(metaclass):
    class EnumRegisteringMetaclass(metaclass, EnumMeta):
        pass

    def from_enum(cls, enum, description=None, deprecation_reason=None):
        description = description or enum.__doc__
        meta_dict = {
            "enum": enum,
            "description": description,
            "deprecation_reason": deprecation_reason,
        }
        meta_class = type("Meta", (object,), meta_dict)
        return type(meta_class.enum.__name__, (cls,), {"Meta": meta_class})

    Enum = EnumRegisteringMetaclass('Enum', (graphene.Enum,), {'from_enum': classmethod(from_enum)})
    setattr(Enum, '__dauphinCoreType', True)
    return Enum 
Example 13
Project: MR   Author: bkerler   File: javaobj.py    License: MIT License 6 votes vote down vote up
def do_enum(self, parent=None, ident=0):
        """
        Handles a TC_ENUM opcode

        :param parent:
        :param ident: Log indentation level
        :return: A JavaEnum object
        """
        # TC_ENUM classDesc newHandle enumConstantName
        enum = JavaEnum()
        _, classdesc = self._read_and_exec_opcode(
            ident=ident + 1,
            expect=(self.TC_CLASSDESC, self.TC_PROXYCLASSDESC,
                    self.TC_NULL, self.TC_REFERENCE))
        enum.classdesc = classdesc
        self._add_reference(enum, ident)
        _, enumConstantName = self._read_and_exec_opcode(
            ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE))
        enum.constant = enumConstantName
        return enum 
Example 14
Project: guider   Author: iipeace   File: CppHeaderParser.py    License: GNU General Public License v2.0 6 votes vote down vote up
def evaluate_enum_stack(self):
        """Create an Enum out of the name stack"""
        debug_print( "evaluating enum" )
        newEnum = CppEnum(self.nameStack)
        if len(list(newEnum.keys())):
            if len(self.curClass):
                newEnum["namespace"] = self.cur_namespace(False)
                klass = self.classes[self.curClass]
                klass["enums"][self.curAccessSpecifier].append(newEnum)
                if self.curAccessSpecifier == 'public' and 'name' in newEnum: klass._public_enums[ newEnum['name'] ] = newEnum
            else:
                newEnum["namespace"] = self.cur_namespace(True)
                self.enums.append(newEnum)
                if 'name' in newEnum and newEnum['name']: self.global_enums[ newEnum['name'] ] = newEnum

            #This enum has instances, turn them into properties
            if "instances" in newEnum:
                instanceType = "enum"
                if "name" in newEnum:
                    instanceType = newEnum["name"]
                for instance in newEnum["instances"]:
                    self.nameStack = [instanceType,  instance]
                    self.evaluate_property_stack()
                del newEnum["instances"] 
Example 15
Project: MR   Author: bkerler   File: javaobj.py    License: MIT License 6 votes vote down vote up
def write_enum(self, obj):
        """
        Writes an Enum value

        :param obj: A JavaEnum object
        """
        # FIXME: the output doesn't have the same references as the real
        # serializable form
        self._writeStruct(">B", 1, (self.TC_ENUM,))

        try:
            idx = self.references.index(obj)
        except ValueError:
            # New reference
            self.references.append(obj)
            logging.debug(
                "*** Adding ref 0x%X for enum: %s",
                len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj)

            self.write_classdesc(obj.get_class())
        else:
            self.write_reference(idx)

        self.write_string(obj.constant) 
Example 16
Project: Email_My_PC   Author: Jackeriss   File: folder_view.py    License: MIT License 6 votes vote down vote up
def make_item_enum(level, flags):
    pidls = []
    nums = """zero one two three four five size seven eight nine ten""".split()
    for i, name in enumerate(nums):
        size = random.randint(0,255)
        sides = 1
        while sides in [1,2]:
            sides = random.randint(0,5)
        is_folder = (i % 2) != 0
        # check the flags say to include it.
        # (This seems strange; if you ask the same folder for, but appear
        skip = False
        if not (flags & shellcon.SHCONTF_STORAGE):
            if is_folder:
                skip = not (flags & shellcon.SHCONTF_FOLDERS)
            else:
                skip = not (flags & shellcon.SHCONTF_NONFOLDERS)
        if not skip:
            data = dict(name=name, size=size, sides=sides, level=level, is_folder=is_folder)
            pidls.append([pickle.dumps(data)])
    return NewEnum(pidls, shell.IID_IEnumIDList)

# start of Utils.cpp port 
Example 17
Project: Gurux.DLMS.Python   Author: Gurux   File: _GXCommon.py    License: GNU General Public License v2.0 6 votes vote down vote up
def getEnum(cls, buff, info):
        value = None
        #  If there is not enough data available.
        if len(buff) - buff.position < 1:
            info.complete = False
            return None
        value = buff.getUInt8()
        if info.xml:
            info.xml.appendLine(info.xml.getDataType(info.type_), None, info.xml.integerToHex(value, 2))
        return GXEnum(value)

    #
    # Get UInt64 value from DLMS data.
    #
    # buff
    # Received DLMS data.
    # info
    # Data info.
    # parsed UInt64 value.
    # 
Example 18
Project: prophy   Author: aurzenligl   File: cpp_full.py    License: MIT License 6 votes vote down vote up
def translate_enum(self, node):
        return (
                'template <>\n' +
                'const char* print_traits<{0}>::to_literal({0} x)\n'.format(node.name) +
                '{\n' +
                _indent(
                    'switch (x)\n' +
                    '{\n' +
                    _indent(
                        ''.join('case {0}: return "{0}";\n'.format(m.name) for m in node.members) +
                        'default: return 0;\n'
                    ) +
                    '}\n'
                ) +
                '}'
        ) 
Example 19
Project: gxpy   Author: GeosoftInc   File: GXMETA.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_attrib_enum(self, ph_object, ph_attrib, value):
        """
        Get an enum value to an attribute (as an integer)
        
        :param ph_object:  Object
        :param ph_attrib:  Attribute
        :param value:      Value to set
        :type  ph_object:  int
        :type  ph_attrib:  int
        :type  value:      int_ref

        .. versionadded:: 5.1.6

        **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_
        """
        value.value = self._get_attrib_enum(ph_object, ph_attrib, value.value) 
Example 20
Project: pytablewriter   Author: thombashi   File: _function.py    License: MIT License 6 votes vote down vote up
def normalize_enum(
    value, enum_class: Type[Enum], validate: bool = True, default: Optional[Enum] = None
):
    if value is None:
        return default

    if isinstance(value, enum_class):
        return value

    try:
        return enum_class[replace_symbol(value.strip(), "_").upper()]
    except AttributeError:
        if validate:
            raise TypeError(
                "value must be a {} or a str: actual={}".format(enum_class, type(value))
            )
    except KeyError:
        if validate:
            raise ValueError(
                "invalid valid found: expected={}, actual={}".format(
                    "/".join([item.name for item in enum_class]), value
                )
            )

    return value 
Example 21
Project: luci-py   Author: luci   File: descriptor_pool.py    License: Apache License 2.0 6 votes vote down vote up
def FindEnumTypeByName(self, full_name):
    """Loads the named enum descriptor from the pool.

    Args:
      full_name (str): The full name of the enum descriptor to load.

    Returns:
      EnumDescriptor: The enum descriptor for the named type.

    Raises:
      KeyError: if the enum cannot be found in the pool.
    """

    full_name = _NormalizeFullyQualifiedName(full_name)
    if full_name not in self._enum_descriptors:
      self._FindFileContainingSymbolInDb(full_name)
    return self._enum_descriptors[full_name] 
Example 22
Project: abseil-py   Author: abseil   File: _defines.py    License: Apache License 2.0 6 votes vote down vote up
def DEFINE_enum(  # pylint: disable=invalid-name,redefined-builtin
    name, default, enum_values, help, flag_values=_flagvalues.FLAGS,
    module_name=None, **args):
  """Registers a flag whose value can be any string from enum_values.

  Instead of a string enum, prefer `DEFINE_enum_class`, which allows
  defining enums from an `enum.Enum` class.

  Args:
    name: str, the flag name.
    default: str|None, the default value of the flag.
    enum_values: [str], a non-empty list of strings with the possible values for
        the flag.
    help: str, the help message.
    flag_values: FlagValues, the FlagValues instance with which the flag will
        be registered. This should almost never need to be overridden.
    module_name: str, the name of the Python module declaring this flag.
        If not provided, it will be computed using the stack trace of this call.
    **args: dict, the extra keyword args that are passed to Flag __init__.
  """
  DEFINE_flag(_flag.EnumFlag(name, default, help, enum_values, **args),
              flag_values, module_name) 
Example 23
Project: pycozmo   Author: zayfod   File: protocol_generator.py    License: MIT License 6 votes vote down vote up
def generate_enum_validation(self, argument: protocol_declaration.EnumArgument):
        if isinstance(argument.data_type, protocol_declaration.UInt8Argument):
            self.f.write('validate_integer("{name}", value.value, 0, 255)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.UInt16Argument):
            self.f.write('validate_integer("{name}", value.value, 0, 65535)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.UInt32Argument):
            self.f.write('validate_integer("{name}", value.value, 0, 4294967295)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.Int8Argument):
            self.f.write('validate_integer("{name}", value.value, -128, 127)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.Int16Argument):
            self.f.write('validate_integer("{name}", value.value, -32768, 32767)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.Int32Argument):
            self.f.write(
                'validate_integer("{name}", value.value, -2147483648, 2147483647)\n'.format(name=argument.name))
        else:
            raise NotImplementedError("Unexpected enum data type '{}' for '{}'".format(
                argument.data_type.__class__.__name__, argument.name)) 
Example 24
Project: lambda-packs   Author: ryfeus   File: descriptor_pool.py    License: MIT License 6 votes vote down vote up
def FindEnumTypeByName(self, full_name):
    """Loads the named enum descriptor from the pool.

    Args:
      full_name: The full name of the enum descriptor to load.

    Returns:
      The enum descriptor for the named type.

    Raises:
      KeyError: if the enum cannot be found in the pool.
    """

    full_name = _NormalizeFullyQualifiedName(full_name)
    if full_name not in self._enum_descriptors:
      self._FindFileContainingSymbolInDb(full_name)
    return self._enum_descriptors[full_name] 
Example 25
Project: pyBreezeChMS   Author: alexortizrosado   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def make_enum(enum_type='enum', base_classes=None, methods=None, **attrs):
  """
  Generates a enumeration with the given attributes.
  """
  # Enumerations can not be initalized as a new instance
  def __init__(instance, *args, **kwargs):
    raise RuntimeError('%s types can not be initialized.' % enum_type)

  if base_classes is None:
    base_classes = ()

  if methods is None:
    methods = {}

  base_classes = base_classes + (object,)
  for k, v in methods.items():
    methods[k] = classmethod(v)

  attrs['enums'] = attrs.copy()
  methods.update(attrs)
  methods['__init__'] = __init__
  return type(enum_type, base_classes, methods) 
Example 26
Project: RedzSIGINT   Author: iamredshift   File: redz-sigint.py    License: GNU General Public License v3.0 6 votes vote down vote up
def convert_analyze_to_enum(arg):
        lowerCase = arg.lower()

        if lowerCase == 'capsoi':
            return 1
        elif lowerCase == 'demodsoi':
            return 2
        elif lowerCase == 'basicanalyzesoi':
            return 3
        elif lowerCase == 'downsamplesoi':
            return 5
        elif lowerCase == 'clockrecoverysoi':
            return 6
        elif lowerCase == 'replaysoi':
            return 7
        else:
            return 1000 
Example 27
Project: tartiflette   Author: tartiflette   File: schema.py    License: MIT License 6 votes vote down vote up
def add_enum_definition(self, enum_definition: "GraphQLEnumType") -> None:
        """
        Adds a GraphQLScalarType to the defined scalar list.
        :param enum_definition: GraphQLEnumType to add
        :type enum_definition: GraphQLEnumType
        """
        if enum_definition.name in self._enum_definitions:
            raise RedefinedImplementation(
                "new GraphQL enum definition `{}` "
                "overrides existing enum definition `{}`.".format(
                    enum_definition.name,
                    repr(self._enum_definitions.get(enum_definition.name)),
                )
            )

        self._enum_definitions[enum_definition.name] = enum_definition
        self._input_types.append(enum_definition.name)
        self.add_type_definition(enum_definition) 
Example 28
Project: apitools   Author: google   File: encoding_helper.py    License: Apache License 2.0 6 votes vote down vote up
def AddCustomJsonEnumMapping(enum_type, python_name, json_name,
                             package=None):  # pylint: disable=unused-argument
    """Add a custom wire encoding for a given enum value.

    This is primarily used in generated code, to handle enum values
    which happen to be Python keywords.

    Args:
      enum_type: (messages.Enum) An enum type
      python_name: (basestring) Python name for this value.
      json_name: (basestring) JSON name to be used on the wire.
      package: (NoneType, optional) No effect, exists for legacy compatibility.
    """
    if not issubclass(enum_type, messages.Enum):
        raise exceptions.TypecheckError(
            'Cannot set JSON enum mapping for non-enum "%s"' % enum_type)
    if python_name not in enum_type.names():
        raise exceptions.InvalidDataError(
            'Enum value %s not a value for type %s' % (python_name, enum_type))
    field_mappings = _JSON_ENUM_MAPPINGS.setdefault(enum_type, {})
    _CheckForExistingMappings('enum', enum_type, python_name, json_name)
    field_mappings[python_name] = json_name 
Example 29
Project: pigaios   Author: joxeankoret   File: clang_exporter.py    License: GNU General Public License v3.0 6 votes vote down vote up
def visit_ENUM_DECL(self, cursor):
    #print("Visiting ENUM DECL")
    value = 0
    for children in cursor.get_children():
      tokens = list(children.get_tokens())
      if len(tokens) == 0:
        # XXX:FIXME: I'm ignoring it too fast, I should take a careful look into
        # it to be sure what should I do here...
        break

      name = tokens[0].spelling
      if len(tokens) == 3:
        value = get_clean_number(tokens[2].spelling)

      # Some error parsing partial source code were an enum member has been
      # initialized to a macro that we know nothing about...
      if type(value) is str:
        return True

      self.enums[name] = value
      if len(tokens) == 1:
        value += 1

    return True 
Example 30
Project: OpenXR-SDK-Source   Author: KhronosGroup   File: xml_consistency.py    License: Apache License 2.0 6 votes vote down vote up
def check_enum_naming(self, enum_type):
        stripped_enum_type, tag = self.strip_extension_tag(enum_type)
        end = "_{}".format(tag) if tag else ""
        if stripped_enum_type.endswith("FlagBits"):
            end = "_BIT" + end
            stripped_enum_type = stripped_enum_type.replace("FlagBits", "")
        start = self.conventions.generate_structure_type_from_name(stripped_enum_type).replace("XR_TYPE", "XR") + "_"

        value_names = get_enum_value_names(self.db.registry, enum_type)
        for name in value_names:
            if not name.startswith(start):
                self.record_error('Got an enum value whose name does not match the pattern: got', name,
                                  'but expected something that started with', start, 'due to typename being', enum_type)
            if end and not name.endswith(end):
                self.record_error('Got an enum value whose name does not match the pattern: got', name,
                                  'but expected something that ended with', end, 'due to typename being', enum_type) 
Example 31
Project: OpenXR-SDK-Source   Author: KhronosGroup   File: automatic_source_generator.py    License: Apache License 2.0 6 votes vote down vote up
def getTypeNameEnumTuple(self, param):
        typename = ''
        name = ''
        enum = ''
        for elem in param:
            if elem.tag == 'type':
                typename = noneStr(elem.text)
            elif elem.tag == 'name':
                name = noneStr(elem.text)
            elif elem.tag == 'enum':
                enum = noneStr(elem.text)
        return (typename, name, enum)

    # Retrieve the value of the len tag
    #   self            the AutomaticSourceOutputGenerator object
    #   param           the XML parameter information to access 
Example 32
Project: Fluid-Designer   Author: Microvellum   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_image_enum_previews(path,key,force_reload=False):
    """ Returns: ImagePreviewCollection
        Par1: path - The path to collect the images from
        Par2: key - The dictionary key the previews will be stored in
    """
    enum_items = []
    if len(key.my_previews) > 0:
        return key.my_previews
    
    if path and os.path.exists(path):
        image_paths = []
        for fn in os.listdir(path):
            if fn.lower().endswith(".png"):
                image_paths.append(fn)

        for i, name in enumerate(image_paths):
            filepath = os.path.join(path, name)
            thumb = key.load(filepath, filepath, 'IMAGE',force_reload)
            filename, ext = os.path.splitext(name)
            enum_items.append((filename, filename, filename, thumb.icon_id, i))
    
    key.my_previews = enum_items
    key.my_previews_dir = path
    return key.my_previews 
Example 33
Project: apitools   Author: google   File: message_registry.py    License: Apache License 2.0 6 votes vote down vote up
def AddEnumDescriptor(self, name, description,
                          enum_values, enum_descriptions):
        """Add a new EnumDescriptor named name with the given enum values."""
        message = extended_descriptor.ExtendedEnumDescriptor()
        message.name = self.__names.ClassName(name)
        message.description = util.CleanDescription(description)
        self.__DeclareDescriptor(message.name)
        for index, (enum_name, enum_description) in enumerate(
                zip(enum_values, enum_descriptions)):
            enum_value = extended_descriptor.ExtendedEnumValueDescriptor()
            enum_value.name = self.__names.NormalizeEnumName(enum_name)
            if enum_value.name != enum_name:
                message.enum_mappings.append(
                    extended_descriptor.ExtendedEnumDescriptor.JsonEnumMapping(
                        python_name=enum_value.name, json_name=enum_name))
                self.__AddImport('from %s import encoding' %
                                 self.__base_files_package)
            enum_value.number = index
            enum_value.description = util.CleanDescription(
                enum_description or '<no description>')
            message.values.append(enum_value)
        self.__RegisterDescriptor(message) 
Example 34
Project: meta-dataset   Author: google-research   File: trainer.py    License: Apache License 2.0 6 votes vote down vote up
def get_split_enum(split):
  """Returns the Enum value corresponding to the given split.

  Args:
    split: A string, one of TRAIN_SPLIT, VALID_SPLIT, TEST_SPLIT.

  Raises:
    UnexpectedSplitError: split not TRAIN_SPLIT, VALID_SPLIT, or TEST_SPLIT.
  """
  # Get the int representing the chosen split.
  if split == TRAIN_SPLIT:
    split_enum = learning_spec.Split.TRAIN
  elif split == VALID_SPLIT:
    split_enum = learning_spec.Split.VALID
  elif split == TEST_SPLIT:
    split_enum = learning_spec.Split.TEST
  else:
    raise UnexpectedSplitError(split)
  return split_enum 
Example 35
Project: python-asana   Author: Asana   File: custom_fields.py    License: MIT License 6 votes vote down vote up
def update_enum_option(self, enum_option, params={}, **options):
        """Updates an existing enum option. Enum custom fields require at least one enabled enum option.

        Locked custom fields can only be updated by the user who locked the field.

        Returns the full record of the updated enum option.

        Parameters
        ----------
        enum_option : {Gid} Globally unique identifier for the enum option.
        [data] : {Object} Data for the request
          - name : {String} The name of the enum option.
          - [color] : {String} The color of the enum option. Defaults to 'none'.
          - [enabled] : {Boolean} Whether or not the enum option is a selectable value for the custom field.
        """
        path = "/enum_options/%s" % (enum_option)
        return self.client.put(path, params, **options) 
Example 36
Project: pose-thumbnails   Author: jasperges   File: core.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_enum_items(poselib: bpy.types.Action,
                   pcoll: bpy.utils.previews.ImagePreviewCollection):
    """Return the enum items for the thumbnail previews."""

    enum_items = []
    wm = bpy.context.window_manager
    pose_thumbnail_options = wm.pose_thumbnails.options
    show_all_poses = pose_thumbnail_options.show_all_poses
    for i, pose in enumerate(poselib.pose_markers):
        thumbnail = common.get_thumbnail_from_pose(pose)
        if thumbnail:
            image = _load_image(poselib, pcoll, thumbnail.filepath)
        elif show_all_poses:
            image = get_placeholder_image(pcoll)
        else:
            image = None
        if image is not None:
            enum_items.append((
                str(pose.frame),
                pose.name,
                '',
                image.icon_id,
                i,
            ))
    return enum_items 
Example 37
Project: box-python-sdk   Author: box   File: metadata_template.py    License: Apache License 2.0 6 votes vote down vote up
def remove_enum_option(self, field_key, option_key):
        """
        Remove an option from an enum field.

        :param field_key:
            The key of the template field in which the option appears
        :type field_key:
            `unicode`
        :param option_key:
            The key of the enum option to remove
        :type option_key:
            `unicode`
        """
        self.add_operation({
            'op': 'removeEnumOption',
            'fieldKey': field_key,
            'enumOptionKey': option_key,
        }) 
Example 38
Project: BlenderPro   Author: CreativeDesigner3D   File: utils_library.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_folder_enum_previews(path,key):
    """ Returns: ImagePreviewCollection
        Par1: path - The path to collect the folders from
        Par2: key - The dictionary key the previews will be stored in
    """
    enum_items = []
    if len(key.my_previews) > 0:
        return key.my_previews
    
    if path and os.path.exists(path):
        folders = []
        for fn in os.listdir(path):
            if os.path.isdir(os.path.join(path,fn)):
                folders.append(fn)

        for i, name in enumerate(folders):
            filepath = os.path.join(path, name)
            thumb = key.load(filepath, "", 'IMAGE')
            filename, ext = os.path.splitext(name)
            enum_items.append((filename, filename, filename, thumb.icon_id, i))
    
    key.my_previews = enum_items
    key.my_previews_dir = path
    return key.my_previews 
Example 39
Project: pyschema   Author: spotify   File: core.py    License: Apache License 2.0 6 votes vote down vote up
def add_enum(self, enum_definition):
        new_values_set = set(enum_definition.values)
        old_values_set = self._enum_map.get(enum_definition.name)

        if old_values_set is not None and new_values_set != old_values_set:
            warnings.warn(
                "Enum {!r} overwritten! Was: {}, Overwritten by: {}".format(
                    enum_definition.name,
                    old_values_set,
                    new_values_set
                )
            )

        if enum_definition.name is not None:
            self._enum_map[enum_definition.name] = enum_definition.values
        # return the definition to allow the method to be used as a decorator
        return enum_definition 
Example 40
Project: box-python-sdk   Author: box   File: metadata_template.py    License: Apache License 2.0 6 votes vote down vote up
def add_enum_option(self, field_key, option_key):
        """
        Adds a new option to an enum field.

        :param field_key:
            The key of the template field to add the option to
        :type field_key:
            `unicode`
        :param option_key:
            The option to add
        :type option_key:
            `unicode`
        """
        self.add_operation({
            'op': 'addEnumOption',
            'fieldKey': field_key,
            'data': {
                'key': option_key,
            },
        }) 
Example 41
Project: ctypesgen   Author: davidjamesca   File: ctypesparser.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def make_enum_from_specifier(specifier):
    tag = specifier.tag

    enumerators = []
    last_name = None
    for e in specifier.enumerators:
        if e.expression:
            value = e.expression
        else:
            if last_name:
                value = BinaryExpressionNode(
                    "addition",
                    (lambda x, y: x + y),
                    "(%s + %s)",
                    (False, False),
                    IdentifierExpressionNode(last_name),
                    ConstantExpressionNode(1),
                )
            else:
                value = ConstantExpressionNode(0)

        enumerators.append((e.name, value))
        last_name = e.name

    return CtypesEnum(tag, enumerators, src=(specifier.filename, specifier.lineno)) 
Example 42
Project: protorpc   Author: google   File: descriptor.py    License: Apache License 2.0 6 votes vote down vote up
def describe_enum(enum_definition):
  """Build descriptor for Enum class.

  Args:
    enum_definition: Enum class to provide descriptor for.

  Returns:
    Initialized EnumDescriptor instance describing the Enum class.
  """
  enum_descriptor = EnumDescriptor()
  enum_descriptor.name = enum_definition.definition_name().split('.')[-1]

  values = []
  for number in enum_definition.numbers():
    value = enum_definition.lookup_by_number(number)
    values.append(describe_enum_value(value))

  if values:
    enum_descriptor.values = values

  return enum_descriptor 
Example 43
Project: pyparrot   Author: amymcgovern   File: bleConnection.py    License: MIT License 6 votes vote down vote up
def send_enum_command_packet_ack(self, command_tuple, enum_value, usb_id=None):
        """
        Send a command on the ack channel with enum parameters as well (most likely a flip).
        All commandsandsensors except PCMD go on the ack channel per
        http://forum.developer.parrot.com/t/ble-characteristics-of-minidrones/5912/2

        the id of the last command sent (for use in ack) is the send counter (which is incremented before sending)

        :param command_tuple: 3 tuple of the command bytes.  0 padded for 4th byte
        :param enum_value: the enum index
        :return: nothing
        """
        self.characteristic_send_counter['SEND_WITH_ACK'] = (self.characteristic_send_counter['SEND_WITH_ACK'] + 1) % 256
        if (usb_id is None):
            packet = struct.pack("<BBBBBBI", self.data_types['DATA_WITH_ACK'], self.characteristic_send_counter['SEND_WITH_ACK'],
                                 command_tuple[0], command_tuple[1], command_tuple[2], 0,
                                 enum_value)
        else:
            color_print((self.data_types['DATA_WITH_ACK'], self.characteristic_send_counter['SEND_WITH_ACK'],
                         command_tuple[0], command_tuple[1], command_tuple[2], 0, usb_id, enum_value), 1)
            packet = struct.pack("<BBBBHBI", self.data_types['DATA_WITH_ACK'], self.characteristic_send_counter['SEND_WITH_ACK'],
                                 command_tuple[0], command_tuple[1], command_tuple[2],
                                 usb_id, enum_value)
        return self.send_command_packet_ack(packet) 
Example 44
Project: rdbms-subsetter   Author: 18F   File: postgres.py    License: Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def fix_postgres_array_of_enum(connection, tbl):
    "Change type of ENUM[] columns to a custom type"

    for col in tbl.c:
        col_str = str(col.type)
        if col_str.endswith('[]'):  # this is an array
            enum_name = col_str[:-2]
            try:  # test if 'enum_name' is an enum
                enum_ranges = connection.execute('''
                        SELECT enum_range(NULL::%s);
                    ''' % enum_name).fetchone()
                enum_values = sql_enum_to_list(enum_ranges[0])
                enum = ENUM(*enum_values, name=enum_name)
                tbl.c[col.name].type = ArrayOfEnum(enum)
            except sa.exc.ProgrammingError as enum_excep:
                if 'does not exist' in str(enum_excep):
                    pass  # Must not have been an enum
                else:
                    raise 
Example 45
Project: coremltools   Author: apple   File: descriptor_pool.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def FindEnumTypeByName(self, full_name):
    """Loads the named enum descriptor from the pool.

    Args:
      full_name: The full name of the enum descriptor to load.

    Returns:
      The enum descriptor for the named type.

    Raises:
      KeyError: if the enum cannot be found in the pool.
    """

    full_name = _NormalizeFullyQualifiedName(full_name)
    if full_name not in self._enum_descriptors:
      self._FindFileContainingSymbolInDb(full_name)
    return self._enum_descriptors[full_name] 
Example 46
Project: apitools   Author: google   File: descriptor.py    License: Apache License 2.0 6 votes vote down vote up
def describe_enum(enum_definition):
    """Build descriptor for Enum class.

    Args:
      enum_definition: Enum class to provide descriptor for.

    Returns:
      Initialized EnumDescriptor instance describing the Enum class.
    """
    enum_descriptor = EnumDescriptor()
    enum_descriptor.name = enum_definition.definition_name().split('.')[-1]

    values = []
    for number in sorted(enum_definition.numbers()):
        value = enum_definition.lookup_by_number(number)
        values.append(describe_enum_value(value))

    if values:
        enum_descriptor.values = values

    return enum_descriptor 
Example 47
Project: FSeam   Author: FreeYourSoul   File: CppHeaderParser.py    License: MIT License 6 votes vote down vote up
def evaluate_enum_stack(self):
        """Create an Enum out of the name stack"""
        debug_print( "evaluating enum" )
        newEnum = CppEnum(self.nameStack)
        if len(list(newEnum.keys())):
            if len(self.curClass):
                newEnum["namespace"] = self.cur_namespace(False)
                klass = self.classes[self.curClass]
                klass["enums"][self.curAccessSpecifier].append(newEnum)
                if self.curAccessSpecifier == 'public' and 'name' in newEnum: klass._public_enums[ newEnum['name'] ] = newEnum
            else:
                newEnum["namespace"] = self.cur_namespace(True)
                self.enums.append(newEnum)
                if 'name' in newEnum and newEnum['name']: self.global_enums[ newEnum['name'] ] = newEnum

            #This enum has instances, turn them into properties
            if "instances" in newEnum:
                instanceType = "enum"
                if "name" in newEnum:
                    instanceType = newEnum["name"]
                for instance in newEnum["instances"]:
                    self.nameStack = [instanceType,  instance]
                    self.evaluate_property_stack()
                del newEnum["instances"] 
Example 48
Project: maas   Author: maas   File: enum.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def map_enum_reverse(enum_class, ignore=None):
    """Map out an enumeration class as a "value: NAME" dict.

    Works like `map_enum`, but reverse its keys and values so that you can
    look up text representations from the enum's integer value.

    Any keys in `ignore` are left out of the returned dict.  This lets you
    remove the `DEFAULT` entry that some enum classes have.
    """
    if ignore is None:
        ignore = []
    return {
        value: key
        for key, value in map_enum(enum_class).items()
        if key not in ignore
    } 
Example 49
Project: Blender-AnimeHairSupporter   Author: relarar   File: _common.py    License: Apache License 2.0 6 votes vote down vote up
def get_bevel_enum_items():
	items = [
		('Sphere', "円", "", 'MESH_CIRCLE'),
		('2', "2本", "", 'OUTLINER_OB_META'),
		('3', "3本", "", 'COLLAPSEMENU'),
		('Triangle', "三角", "", 'EDITMODE_VEC_HLT'),
		('TriangleLoose', "ゆるやか三角", "", 'PLAY_REVERSE'),
		('Square', "四角", "", 'MESH_PLANE'),
		('SquareLoose', "ゆるやか四角", "", 'LATTICE_DATA'),
		('Diamond', "ひし形", "", 'SPACE3'),
		('DiamondLoose', "ゆるやかひし形", "", 'KEYTYPE_EXTREME_VEC'),
		('Sharp', "シャープ", "", 'LINCURVE'),
		('Leaf', "葉っぱ", "", 'MAN_ROT'),
		('V', "切り込み", "", 'FILE_TICK'),
		('Tilde', "波", "", 'IPO_EASE_IN_OUT'),
		('Step', "段差", "", 'IPO_CONSTANT'),
		('Corrugated', "ギザギザ", "", 'RNDCURVE'),
		('Cloud', "雲", "", 'IPO_ELASTIC'),
		]
	for i, item in enumerate(items): items[i] = tuple(list(item) + [i + 1])
	return items 
Example 50
Project: maas   Author: maas   File: factory.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def pick_enum(self, enum, *, but_not=EMPTY_SET):
        """Pick a random item from an enumeration class.

        :param enum: An enumeration class such as `NODE_STATUS`. Can also be
            an `enum.Enum` subclass.
        :return: The value of one of its items.
        :param but_not: A list of choices' IDs to exclude.
        :type but_not: Sequence.
        """
        if issubclass(enum, Enum):
            return random.choice(
                [value for value in enum if value not in but_not]
            )
        else:
            return random.choice(
                [
                    value
                    for key, value in vars(enum).items()
                    if not key.startswith("_") and value not in but_not
                ]
            ) 
Example 51
Project: BlenderPro   Author: CreativeDesigner3D   File: utils_library.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_image_enum_previews(path,key,force_reload=False):
    """ Returns: ImagePreviewCollection
        Par1: path - The path to collect the images from
        Par2: key - The dictionary key the previews will be stored in
    """
    enum_items = []
    if len(key.my_previews) > 0:
        return key.my_previews
    
    if path and os.path.exists(path):
        image_paths = []
        for fn in os.listdir(path):
            if fn.lower().endswith(".png"):
                image_paths.append(fn)

        for i, name in enumerate(image_paths):
            filepath = os.path.join(path, name)
            thumb = key.load(filepath, filepath, 'IMAGE',force_reload)
            filename, ext = os.path.splitext(name)
            enum_items.append((filename, filename, filename, thumb.icon_id, i))
    
    key.my_previews = enum_items
    key.my_previews_dir = path
    return key.my_previews 
Example 52
Project: ModelZoo   Author: ModelZoo   File: flags.py    License: MIT License 6 votes vote down vote up
def DEFINE_enum_class(name, default, enum_class, help=None, flag_values=_flagvalues.FLAGS, module_name=None, **args):
    """Registers a flag whose value can be the name of enum members.

    Args:
      name: str, the flag name.
      default: Enum|str|None, the default value of the flag.
      enum_class: class, the Enum class with all the possible values for the flag.
      help: str, the help message.
      flag_values: FlagValues, the FlagValues instance with which the flag will
          be registered. This should almost never need to be overridden.
      module_name: str, the name of the Python module declaring this flag.
          If not provided, it will be computed using the stack trace of this call.
      **args: dict, the extra keyword args that are passed to Flag __init__.
    """
    DEFINE_flag(_flag.EnumClassFlag(name, default, help, enum_class, **args),
                flag_values, module_name) 
Example 53
Project: ironpython2   Author: IronLanguages   File: folder_view.py    License: Apache License 2.0 6 votes vote down vote up
def make_item_enum(level, flags):
    pidls = []
    nums = """zero one two three four five size seven eight nine ten""".split()
    for i, name in enumerate(nums):
        size = random.randint(0,255)
        sides = 1
        while sides in [1,2]:
            sides = random.randint(0,5)
        is_folder = (i % 2) != 0
        # check the flags say to include it.
        # (This seems strange; if you ask the same folder for, but appear
        skip = False
        if not (flags & shellcon.SHCONTF_STORAGE):
            if is_folder:
                skip = not (flags & shellcon.SHCONTF_FOLDERS)
            else:
                skip = not (flags & shellcon.SHCONTF_NONFOLDERS)
        if not skip:
            data = dict(name=name, size=size, sides=sides, level=level, is_folder=is_folder)
            pidls.append([pickle.dumps(data)])
    return NewEnum(pidls, shell.IID_IEnumIDList)

# start of Utils.cpp port 
Example 54
Project: vim-gdscript3   Author: calviken   File: script.py    License: MIT License 6 votes vote down vote up
def get_enum_values(line_num):
    lines = [util.strip_line(line_num, util.get_line(line_num))]
    line_count = util.get_line_count()
    while not lines[-1].endswith("}"):
        line_num += 1
        if line_num > line_count:
            return
        lines.append(util.strip_line(line_num, util.get_line(line_num)))
    m = re.match(_ENUM_VALUES_PATTERN, "\n".join(lines), re.DOTALL)
    if m:
        values = [v.strip() for v in m.group(1).replace("\n", ",").split(",")]
        def map_value(v):
            m = re.match("(\w+)(?:\s*=\s*(.*))?", v)
            if m:
                return ConstDecl(-1, m.group(1), m.group(2))
        return list(filter(lambda v: v, map(map_value, values)))


# A token chain is a group of tokens chained via dot accessors.
# "Token" is a loose term referring to anything that produces a value.
# Example:
#     texture.get_data().get_pixel()
# 'texture', 'get_data', and 'get_pixel' all produce values, and are therefore tokens.
#
# A token chain is only considered valid if every token has a discernible type. 
Example 55
Project: RFExplorer-for-Python   Author: RFExplorer   File: RFExplorer.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def GetModelEnumFromText(sText):
    """Returns model enumerator based on text provided

    Parameters:
        sText -- One of "433M", "868M", "915M", "WSUB1G", "2.4G", "WSUB3G", "6G", "WSUB1G_PLUS" or "RFE6GEN"
    Returns:
        RFE_Common.eModel Valid model enumerator or will set to MODEL_NONE if not found
	"""
    eReturn = RFE_Common.eModel.MODEL_NONE

    for nInd in range(len(g_arrModels)):
        if (sText.upper() == g_arrModels[nInd]):
            eReturn = RFE_Common.eModel(nInd)
            break

    return eReturn

#--------------------------------------------------------- 
Example 56
Project: BinderFilter   Author: dxwu   File: types.py    License: MIT License 6 votes vote down vote up
def make_enum_dict(enum_type):
    """Return a dictionary from a program's enum type.

    Arguments:
        enum_type: The enum to compute the dictionary for.

    Returns:
        The dictionary of the enum.

    Raises:
        TypeError: The type is not an enum.
    """

    if enum_type.code != gdb.TYPE_CODE_ENUM:
        raise TypeError("not an enum type")
    enum_dict = {}
    for field in enum_type.fields():
        # The enum's value is stored in "bitpos".
        enum_dict[field.name] = field.bitpos
    return enum_dict 
Example 57
Project: django-more   Author: ashleywaite   File: patches.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ask_remove_enum_values(self, db_type, values):
        """ How to treat records with deleted enum values. """
        # Ordered ensures
        choices = [
            (models.CASCADE, "Cascade - Delete records with removed values"),
            (models.PROTECT, "Protect - Block migrations if records contain removed values"),
            (models.SET_NULL, "Set NULL - Set value to NULL"),
            (models.SET_DEFAULT, "Set default - Set value to field default"),
            (models.SET, "Set value - Provide a one off default now"),
            (models.DO_NOTHING, "Do nothing - Consistency must be handled elsewhere"),
            (None, "Leave it to field definitions")]
        choice, _ = choices[self._choice_input(
            "Enum {db_type} has had {values} removed, "
            "existing records may need to be updated. "
            "Override update behaviour or do nothing and follow field behaviour.".format(
                db_type=db_type,
                values=values),
            [q for (k, q) in choices]) - 1]
        if choice == models.SET:
            return models.SET(self._ask_default())
        return choice 
Example 58
Project: spavro   Author: pluralsight   File: io.py    License: Apache License 2.0 6 votes vote down vote up
def read_enum(self, writers_schema, readers_schema, decoder):
        """
        An enum is encoded by a int, representing the zero-based position
        of the symbol in the schema.
        """
        # read data
        index_of_symbol = decoder.read_int()
        if index_of_symbol >= len(writers_schema.symbols):
            fail_msg = "Can't access enum index %d for enum with %d symbols"\
                                 % (index_of_symbol, len(writers_schema.symbols))
            raise SchemaResolutionException(fail_msg, writers_schema, readers_schema)
        read_symbol = writers_schema.symbols[index_of_symbol]

        # schema resolution
        if read_symbol not in readers_schema.symbols:
            fail_msg = "Symbol %s not present in Reader's Schema" % read_symbol
            raise SchemaResolutionException(fail_msg, writers_schema, readers_schema)

        return read_symbol 
Example 59
Project: ironpython2   Author: IronLanguages   File: win32clipboardDemo.py    License: Apache License 2.0 6 votes vote down vote up
def TestClipboardEnum():
    OpenClipboard()
    try:
        # Enumerate over the clipboard types
        enum = 0
        while 1:
            enum = EnumClipboardFormats(enum)
            if enum==0:
                break
            assert IsClipboardFormatAvailable(enum), "Have format, but clipboard says it is not available!"
            n = cf_names.get(enum,"")
            if not n:
                try:
                    n = GetClipboardFormatName(enum)
                except error:
                    n = "unknown (%s)" % (enum,)

            print "Have format", n
        print "Clipboard enumerator tests worked correctly"
    finally:
        CloseClipboard() 
Example 60
Project: ModelZoo   Author: ModelZoo   File: flags.py    License: MIT License 6 votes vote down vote up
def DEFINE_multi_enum(name, default, enum_values, help=None, flag_values=_flagvalues.FLAGS, case_sensitive=True,
                      **args):
    """Registers a flag whose value can be a list strings from enum_values.

    Use the flag on the command line multiple times to place multiple
    enum values into the list.  The 'default' may be a single string
    (which will be converted into a single-element list) or a list of
    strings.

    Args:
      name: str, the flag name.
      default: Union[Iterable[Text], Text, None], the default value of the flag;
          see `DEFINE_multi`.
      enum_values: [str], a non-empty list of strings with the possible values for
          the flag.
      help: str, the help message.
      flag_values: FlagValues, the FlagValues instance with which the flag will
          be registered. This should almost never need to be overridden.
      case_sensitive: Whether or not the enum is to be case-sensitive.
      **args: Dictionary with extra keyword args that are passed to the
          Flag __init__.
    """
    parser = _argument_parser.EnumParser(enum_values, case_sensitive)
    serializer = _argument_parser.ArgumentSerializer()
    DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)