def convertControlTypes(ct): """This functions takes controlTypes module as parameter. It recreates Role and State enumerations if they are missing for this module. """ import enum try: ct.Role except AttributeError: # Re-create Role enum Role = enum.IntEnum( 'Role', { v[len('ROLE_'):]: getattr(ct, v) for v in dir(ct) if v.startswith('ROLE_') }) ct.Role = Role try: ct.State except AttributeError: # Re-create State enum State = enum.IntEnum( 'State', { v[len('STATE_'):]: getattr(ct, v) for v in dir(ct) if v.startswith('STATE_') }) ct.State = State return ct
class AdaptThresh(): name = 'adaptiveThreshold' thresh_type_names = \ ['BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV'] ThreshTypes = enum.IntEnum('Thresh', thresh_type_names) cv2_thresh_types = \ [cv2.THRESH_BINARY, cv2.THRESH_BINARY_INV, cv2.THRESH_TRUNC, cv2.THRESH_TOZERO, cv2.THRESH_TOZERO_INV] adapt_method_names = \ ['MEAN_C', 'GAUSSIAN_C'] AdaptMethods = enum.IntEnum('Adapt', adapt_method_names) cv2_adapt_methods = \ [cv2.ADAPTIVE_THRESH_MEAN_C, cv2.ADAPTIVE_THRESH_GAUSSIAN_C] @classmethod def get_image(cls, root, obj, _): if len(obj.image.shape) is not 2: raise error.ModuleError('input image must be one color only!') mv = int(root.find('maxValue').text) bs = int(root.find('blockSize').text) p1 = int(root.find('param1').text) am = AdaptThresh.AdaptMethods[str(root.find('adaptiveMethod').text)] tt = AdaptThresh.ThreshTypes[str(root.find('thresholdType').text)] cv2_am = cls.cv2_adapt_methods[am - 1] cv2_tt = cls.cv2_thresh_types[tt - 1] image = cv2.adaptiveThreshold(obj.image, mv, cv2_am, cv2_tt, bs, p1) return ImageObj(image, obj.code, obj.contours)
class FindCnt(): name = 'findContours' mode_names = ['LIST', 'EXTERNAL', 'CCOMP', 'TREE'] Modes = enum.IntEnum('ContourMode', mode_names) cv2_modes = \ [cv2.RETR_LIST, cv2.RETR_EXTERNAL, cv2.RETR_CCOMP, cv2.RETR_TREE] method_names = ['NONE', 'SIMPLE', 'TC89_L1', 'TC89_KCOS'] Methods = enum.IntEnum('ContourMethod', method_names) cv2_methods = \ [cv2.CHAIN_APPROX_NONE, cv2.CHAIN_APPROX_SIMPLE, cv2.CHAIN_APPROX_TC89_L1, cv2.CHAIN_APPROX_TC89_KCOS] @classmethod def get_image(cls, root, obj, _): mode = cls.Modes[str(root.find('mode').text)] method = cls.Methods[str(root.find('method').text)] cv2_mode = cls.cv2_modes[mode - 1] cv2_method = cls.cv2_methods[method - 1] if len(obj.image.shape) is not 2: raise error.ModuleError('input image should be one color only!') image = obj.image.copy() contours, hierarchy = cv2.findContours(image, cv2_mode, cv2_method) return ImageObj(image, obj.code, contours)
def roles(self, names: List[str]): if set(names) == set(self.roles): return self.Roles = enum.IntEnum( "Roles", {n: i for i, n in enumerate(names, QtCore.Qt.UserRole)}) self.rolesChanged.emit(list(names))
class Thresh(): name = 'threshold' thresh_type_names = \ ['BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV'] ThreshTypes = enum.IntEnum('Thresh', thresh_type_names) cv2_thresh_types = \ [cv2.THRESH_BINARY, cv2.THRESH_BINARY_INV, cv2.THRESH_TRUNC, cv2.THRESH_TOZERO, cv2.THRESH_TOZERO_INV] @classmethod def get_image(cls, root, obj, _): thresh = int(root.find('thresh').text) max_val = int(root.find('maxVal').text) thresh_type_str = str(root.find('threshType').text) thresh_type = cls.ThreshTypes[thresh_type_str] cv2_thresh_type = cls.cv2_thresh_types[thresh_type - 1] otsu_bool = distutils.util.strtobool(str(root.find('otsu').text)) if otsu_bool: if len(obj.image.shape) is not 2: raise error.ModuleError('input image must be one color only!') thresh = 0 cv2_thresh_type = cv2_thresh_type + cv2.THRESH_OTSU _, image = cv2.threshold(obj.image, thresh, max_val, cv2_thresh_type) return ImageObj(image, obj.code, obj.contours)
def __init__(self, name, data, webChannel): self._id = name self._webChannel = webChannel webChannel.objects[name] = self # override the class so that we can dynamically add properties cls = self.__class__ self.__class__ = type(cls.__name__ + '-' + name, (cls, ), {}) self.__class__.__doc__ = "Interface for remote object {0}".format(name) # List of callbacks that get invoked upon signal emission self._objectSignals = {} # Cache of all properties, updated when a notify signal is emitted self._propertyCache = {} for method in data["methods"]: self._addMethod(method) for prop in data["properties"]: self._bindGetterSetter(prop) for signal in data["signals"]: self._addSignal(signal) for name, values in data.get("enums", {}).items(): setattr(self.__class__, name, enum.IntEnum(name, values))
def doEnumeration(self, tree): #enumerators = [] #for enumerator in tree.enumerators: # enumerators.append(Enumerator(enumerator.value.tag, enumerator.value.constant)) return enum.IntEnum( tree.tag or '', [(e.value.tag, e.value.constant) for e in tree.enumerators]) # Enumeration(tree.tag, enumerators)
def _make_enum(prefix): name = _constant_to_camel(prefix) values = {} for k, v in vars(_lib).items(): if not k.startswith(prefix): continue values[_constant_to_camel(k[len(prefix):])] = v # IntEnum by design; there are different "enum"s for each schema. globals()[name] = enum.IntEnum(name, values)
def enum_convert(name, module, filter): module_globals = vars(sys.modules[module]) members = { name: value for name, value in module_globals.items() if filter(name) } cls = enum.IntEnum(name, members, module=module) module_globals.update(cls.__members__) module_globals[name] = cls return cls
def __make_enum(cls, enum_descriptor: EnumDescriptor) -> type: enum_cls = _REGISTRY.get(enum_descriptor.full_name) if enum_cls is None: enum_cls = enum.IntEnum( enum_descriptor.name, {d.name: d.number for d in enum_descriptor.values}) enum_cls.__module__ = cls.__VIRTUAL_MODULE _REGISTRY[enum_descriptor.full_name] = enum_cls return enum_cls
def get_enum_str(quantity): """Returns the enum label of an enumerated data type :param quantity: object The quantity object of a DevEnum attribute :return: str Current string value of a DevEnum attribute """ EnumClass = enum.IntEnum("EnumLabels", quantity.meta["enum_labels"], start=0) return EnumClass(quantity.last_val).name
def test_intenum_collections(self): self.instance = Instance(self.solver) self.instance.add_string(""" enum TT; % array[int] of var TT: arr_t; var set of TT: set_t; """) TT = enum.IntEnum("TT", ["one", "two", "three"]) self.instance["TT"] = TT # TODO: self.instance["arr_t"] = [TT(3), TT(2), TT(1)] self.instance["set_t"] = {TT(2), TT(1)} result = self.instance.solve() # TODO: assert result["arr_t"] == [TT(3), TT(2), TT(1)] assert result["set_t"] == {TT(1), TT(2)}
def tables(self): """ enum tables in a database returns: a table name from Enum also, assigns table names as a list in self.tables_list usage:: core.sql.tables.table_name """ tables = self.engine.table_names() en = enum.IntEnum("tables", tables) self.tables_list = [e.name for e in en] return en
def Enum(enum_cls): items = { key: val for key, val in inspect.getmembers(enum_cls) if not key.startswith("__") and not key.endswith("__") } int_enum_cls = enum.IntEnum(enum_cls.__name__, items) def code(self, representer): enum_base, key = str(self).split('.') enum_base = representer.make_rel_name(enum_cls.__module__, enum_base) return '.'.join([enum_base, key]) int_enum_cls.__code__ = code int_enum_cls.__module__ = enum_cls.__module__ return int_enum_cls
class Pyocr(): name = 'PyOCR' psmodes_names = \ ['Orientation_and_script_detection_(OSD)_only.', 'Automatic_page_segmentation_with_OSD.', 'Automatic_page_segmentation_but_no_OSD_or_OCR.', 'Fully_automatic_page_segmentation_but_no_OSD._(Default)', 'Assume_a_single_column_of_text_of_variable_sizes.', 'Assume_a_single_uniform_block_of_vertically_aligned_text.', 'Assume_a_single_uniform_block_of_text.', 'Treat_the_image_as_a_single_text_line.', 'Treat_the_image_as_a_single_word.', 'Treat_the_image_as_a_single_word_in_a_circle.', 'Treat_the_image_as_a_single_character.'] PSModes = enum.IntEnum('PageSegmentationMode', psmodes_names) def __init__(self): self.tools = pyocr.get_available_tools() if len(self.tools) == 0: raise error.ModuleError('No OCR tool found') self.tool_names = map(lambda n: n.get_name(), self.tools) self.setTool(self.tool_names[0]) def setTool(self, tool_name): for tool in self.tools: if tool.get_name() == tool_name: self.tool = tool break self.lang_names = self.tool.get_available_languages() def get_image(self, root, obj, _): lang = str(root.find('lang').text) psmode = self.PSModes[str(root.find('psmode').text)] - 1 image = obj.image.copy() builder = pyocr.builders.WordBoxBuilder(tesseract_layout=psmode) res = self.tool.image_to_string(Image.fromarray(image), lang=lang, builder=builder) for d in res: print d.content cv2.rectangle(image, d.position[0], d.position[1], (0, 0, 255), 2) cv2.putText(image, (d.content).encode('utf-8'), d.position[0], cv2.FONT_HERSHEY_PLAIN, 8, (0, 0, 0)) return ImageObj(image, obj.code, obj.contours)
def enum_type_to_class(type: Type, name: str, exclude: Container[str] = (), prefix: str = "") -> enum.IntEnum: """ Get an :class:`enum.IntEnum` class from an enumerated :class:`drgn.Type`. :param type: The enumerated type to convert. :type type: :class:`drgn.Type` :param name: The name of the ``IntEnum`` type to create. :param exclude: Container (e.g., list or set) of enumerator names to exclude from the created ``IntEnum``. :param prefix: Prefix to strip from the beginning of enumerator names. """ enumerators = [(name[len(prefix):] if name.startswith(prefix) else name, value) for (name, value) in type.enumerators if name not in exclude] return enum.IntEnum(name, enumerators)
def enum_type_to_class(type: Type, name: str, exclude: Container[str] = (), prefix: str = "") -> typing.Type[enum.IntEnum]: """ Get an :class:`enum.IntEnum` class from an enumerated :class:`drgn.Type`. :param type: The enumerated type to convert. :param name: The name of the ``IntEnum`` type to create. :param exclude: Container (e.g., list or set) of enumerator names to exclude from the created ``IntEnum``. :param prefix: Prefix to strip from the beginning of enumerator names. """ if type.enumerators is None: raise TypeError("enum type is incomplete") enumerators = [(name[len(prefix):] if name.startswith(prefix) else name, value) for (name, value) in type.enumerators if name not in exclude] return enum.IntEnum(name, enumerators) # type: ignore # python/mypy#4865
def __init__(self, nareas, arealabels=None, maxrangesize=None, labelsep=''): assert len(arealabels) == nareas self.nareas = nareas if arealabels is None: if nareas <= 26: arealabels = tuple(string.ascii_uppercase[:nareas]) else: arealabels = [ 'A{}'.format(i) for i in range(nareas) ] labelsep = labelsep or '+' self.arealabels = arealabels self.areas = enum.IntEnum('areas', arealabels, start=0) self.labelsep = labelsep self.maxrangesize = maxrangesize self.Dg = igraph.Graph() self.Dg.add_vertices(nareas) self.Dg.vs['name'] = self.arealabels self.Qg = igraph.Graph()
def define_routes(self): """ Method defining the routes in the FastAPI app, to display the right HTML file. """ # Define the pages' routes for route, html_file in self.files.items(): @self.fapi.get(route) def index(): return FileResponse(html_file) # Define the callback route if len(self.callbacks) != 0: # Define a dynamic enum to ensure only specific callback ID are valid cbe = enum.IntEnum( 'CallbackEnum', {str(c_id): c_id for c_id in self.callbacks.keys()}) @self.fapi.post("/callback/{callback_id}") def callback(callback_id: cbe, inputs: Dict[str, str]): page, ajax = self.callbacks[callback_id] return ajax(page, inputs)
class CvtColor(): name = 'cvtColor' code_names = ['BGR', 'RGB', 'HSV', 'HLS', 'GRAY'] Codes = enum.IntEnum('Color', code_names) cv2_cvt_codes = \ [[None, cv2.COLOR_BGR2RGB, cv2.COLOR_BGR2HSV, cv2.COLOR_BGR2HLS, cv2.COLOR_BGR2GRAY], [cv2.COLOR_RGB2BGR, None, cv2.COLOR_RGB2HSV, cv2.COLOR_RGB2HLS, cv2.COLOR_RGB2GRAY], [cv2.COLOR_HSV2BGR, cv2.COLOR_HSV2RGB, None, None, None], [cv2.COLOR_HLS2BGR, cv2.COLOR_HLS2RGB, None, None, None], [cv2.COLOR_GRAY2BGR, cv2.COLOR_GRAY2RGB, None, None, None]] @classmethod def get_image(cls, root, obj, _): code = cls.Codes[str(root.find('code').text)] cv2_cvt_code = cls.cv2_cvt_codes[obj.code - 1][code - 1] if cv2_cvt_code is None: return ImageObj(obj.image, obj.code, obj.contours) else: image = cv2.cvtColor(obj.image, cv2_cvt_code) return ImageObj(image, code, obj.contours)
def real_decorator(cls): cls.__init__ = initdecorator(cls.__init__) if not hasattr(cls, "SRData"): Idx = enum.IntEnum( "Idx", {n: i for i, n in enumerate(colnames)}, ) cls.SRData = type("SRData", (NoInstances, ), { "name": name, "Idx": Idx }) for pname, pattr in property_attr.items(): if not hasattr(cls, pname): setattr(cls, pname, property(*pattr)) for mname, meth in method.items(): if not hasattr(cls, mname): setattr(cls, mname, meth) for colname in colnames: a0 = f'srdata{colname}' if not hasattr(cls, a0): setattr(cls, a0, property(srdatafgetfactory(colname))) if not hasattr(cls, colname): propertyattrs = [None] * 3 valattrs = valattrmapping.get(colname, [a0]) propertyattrs[0] = srdatavalfgetfactory(colname, valattrs) if valsettermapping.get(colname, True): propertyattrs[1] = srdatavalfsetfactory(colname) if valdeletermapping.get(colname, True): propertyattrs[2] = srdatavalfdelfactory(colname) setattr(cls, colname, property(*propertyattrs)) a1 = f'{colname}isset' if not hasattr(cls, a1): setattr(cls, a1, property(issetfactory(colname))) if name is not None: setattr(cls, "savesrdata", classmethod(savesrdata)) return cls
def convert_fields_to_struct_fields(fields, verbose=False): total_bits = 0 struct_fields = [] for identifier, op, options in fields: s_field = None if op == "&": bits = len(options) description = f"{bits}-bit bitfield" f_enum = enum.IntFlag( identifier, [(op, 1 << i) for (i, op) in enumerate(options)] ) s_field = identifier / construct.FlagsEnum( construct.BitsInteger(bits), f_enum ) elif op == "|": bits = math.ceil(math.log2(len(options))) description = f"{bits}-bit enum" if set(options) == {True, False}: s_field = identifier / construct.Flag else: f_enum = enum.IntEnum( identifier, [(op, 1 << i) for (i, op) in enumerate(options)] ) s_field = identifier / construct.Enum( construct.BitsInteger(bits), f_enum ) struct_fields.append(s_field) if verbose: print(f"{identifier:15}: {description} ({len(options)} options)") assert bits == s_field.sizeof() total_bits += bits if verbose: print(f"Total bits: {total_bits}") return (struct_fields, total_bits)
from fixorchestra.orchestration import * __author__ = 'tom' beginstring = 'FIX.4.4' import enum class StrEnum(str, enum.Enum): def __str__(self): return str(self.value) orchestration = Orchestration('fix_repository_4_4.xml') fixtags = enum.IntEnum( 'Tags', { tag.name: tag_number for tag_number, tag in orchestration.fields_by_tag.items() }) msgtype = StrEnum('MsgType', { message.name: message.msg_type for message in orchestration.messages.values() })
# others "CONN_DELETE_TCB", "AF_LINK", ] # ===================================================================== # --- globals # ===================================================================== CONN_DELETE_TCB = "DELETE_TCB" ERROR_PARTIAL_COPY = 299 if enum is None: AF_LINK = -1 else: AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': -1}) AF_LINK = AddressFamily.AF_LINK TCP_STATUSES = { cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED, cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT, cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV, cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1, cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2, cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT, cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE, cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK, cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN, cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING, cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB,
class CIFError(ConversionError): pass class ScheduleError(ConversionError): pass one_day = datetime.timedelta(days=1) def dts_format(dts, sec=False): if isinstance(dts, str): return dts if isinstance(dts, datetime.timedelta): dts = dts.total_seconds() dts_days, dts = divmod(int(dts), 24 * 3600) dts = str(datetime.time(dts // 3600, (dts % 3600) // 60, dts % 60, dts % 1)) if not sec: dts = dts.rsplit(':', 1)[0] if dts_days: dts = '{}+{}'.format(dts_days, dts) return dts GTFSRouteType = enum.IntEnum( 'RouteType', 'light_rail subway rail bus ferry cable_car gondola funicular spacecraft', start=0 ) GTFSEmbarkType = enum.IntEnum('EmbarkType', 'regular none phone driver', start=0) GTFSExceptionType = enum.IntEnum('ExceptionType', 'added removed') TimespanMerge = collections.namedtuple('TSMerge', 'op span') TimespanMergeOp = enum.IntEnum( 'TSMergeOp', 'none same inc inc_diff_weekdays overlap bridge', start=0 ) TimespanDiff = collections.namedtuple('TSDiff', 'op spans') TimespanDiffOp = enum.IntEnum('TSDiffOp', 'none full split move exc', start=0) class TimespanEmpty(Exception): pass @ft.total_ordering class Timespan:
}: return True elif re.match('BUTTON\d+MOUSE', self.name): return True elif self in {EventType.PEN, EventType.ERASER}: return True elif (EventType['ZERO'].value <= self.value <= EventType[key]): return True elif EventType['F1'].value <= self.value <= EventType['F19']: return True return False event_type_enum_items = bpy.types.Event.bl_rna.properties['type'].enum_items EventType = enum.IntEnum('EventType', [(e.identifier, e.value) for e in event_type_enum_items]) EventType.has_release_event = has_release_event EventType.names = {e.identifier: e.name for e in event_type_enum_items} ############################################################################### # Operator ############################################################################### def intersect_aabb(min1, max1, min2, max2): """from isect_aabb_aabb_v3() """ for i in range(len(min1)): if max1[i] < min2[i] or max2[i] < min1[i]: return False return True
# Number of clock ticks per second CLOCK_TICKS = os.sysconf("SC_CLK_TCK") PAGESIZE = os.sysconf("SC_PAGE_SIZE") BOOT_TIME = None # set later # Used when reading "big" files, namely /proc/{pid}/smaps and /proc/net/*. # On Python 2, using a buffer with open() for such files may result in a # speedup, see: https://github.com/giampaolo/psutil/issues/708 BIGGER_FILE_BUFFERING = -1 if PY3 else 8192 LITTLE_ENDIAN = sys.byteorder == 'little' if PY3: FS_ENCODING = sys.getfilesystemencoding() if enum is None: AF_LINK = socket.AF_PACKET else: AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': int(socket.AF_PACKET)}) AF_LINK = AddressFamily.AF_LINK # ioprio_* constants http://linux.die.net/man/2/ioprio_get if enum is None: IOPRIO_CLASS_NONE = 0 IOPRIO_CLASS_RT = 1 IOPRIO_CLASS_BE = 2 IOPRIO_CLASS_IDLE = 3 else: class IOPriority(enum.IntEnum): IOPRIO_CLASS_NONE = 0 IOPRIO_CLASS_RT = 1 IOPRIO_CLASS_BE = 2 IOPRIO_CLASS_IDLE = 3
import enum from sqlalchemy import and_, create_engine from sqlalchemy.exc import SQLAlchemyError, IntegrityError from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool from sqlalchemy.sql.expression import desc import query from db.malware.models import * from db.malware.models import _Config from db.malware.query import MalwareQuery from libs.objects import File, Singleton InsertRet = enum.IntEnum('InsertRet', 'ok duplicate error') class Database: __metaclass__ = Singleton def __init__(self, cfg='api.conf'): self.engine = create_engine(Config(cfg).api.database, poolclass=NullPool) self.engine.echo = False self.engine.pool_timeout = 60 Base.metadata.create_all(self.engine) self.Session = sessionmaker(bind=self.engine) self._session = None self.user = None def set_user(self, user):
S = ord("j") W = ord("h") class CompassIntercardinalDirection(enum.IntEnum): NE = ord("u") SE = ord("n") SW = ord("b") NW = ord("y") # Merge the above. CompassDirection = enum.IntEnum( "CompassDirection", { **CompassCardinalDirection.__members__, **CompassIntercardinalDirection.__members__, }, ) class CompassCardinalDirectionLonger(enum.IntEnum): N = ord("K") E = ord("L") S = ord("J") W = ord("H") class CompassIntercardinalDirectionLonger(enum.IntEnum): NE = ord("U") SE = ord("N")
import datetime import enum import pkg_resources from PyQt5.QtCore import pyqtSlot, Qt, QSize from PyQt5.QtWidgets import (QDialog, QLabel, QTextEdit, QPushButton, QVBoxLayout, QHBoxLayout, QCheckBox, QDialogButtonBox, QApplication, QMessageBox) import qutebrowser from qutebrowser.utils import version, log, utils, objreg from qutebrowser.misc import (miscwidgets, autoupdate, msgbox, httpclient, pastebin) from qutebrowser.config import config, configfiles Result = enum.IntEnum('Result', ['restore', 'no_restore'], start=QDialog.Accepted + 1) def parse_fatal_stacktrace(text): """Get useful information from a fatal faulthandler stacktrace. Args: text: The text to parse. Return: A tuple with the first element being the error type, and the second element being the first stacktrace frame. """ lines = [ r'(?P<type>Fatal Python error|Windows fatal exception): (?P<msg>.*)', r' *',