Python builtins.hex() Examples

The following are 26 code examples of builtins.hex(). 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 also want to check out all available functions/classes of the module builtins , or try the search function .
Example #1
Source File: backend.py    From neon with Apache License 2.0 6 votes vote down vote up
def __str__(self):
        s = '(' + str(self[0])
        s += ', '
        if isinstance(self[1], Tensor):
            if self[1].name and self[1].name is not None:
                s += self[1].name
            else:
                s += 'tensor-' + hex(id(self[1]))
        else:
            s += str(self[1])
        s += ', '
        if isinstance(self[2], Tensor):
            if self[2].name and self[2].name is not None:
                s += self[2].name
            else:
                s += 'tensor-' + hex(id(self[2]))
        else:
            s += str(self[2])
        s += ')'
        return s 
Example #2
Source File: usbdriver.py    From alienfx with GNU General Public License v3.0 6 votes vote down vote up
def release(self):
        """ Release control to libusb of the AlienFX controller."""
        if not self._control_taken:
            return
        try:
            usb.util.release_interface(self._dev, 0)
        except USBError as exc: 
            logging.error(
                "Cant release interface. Error : {}".format(exc.strerror))
        try:
            self._dev.attach_kernel_driver(0)
        except USBError as exc: 
            logging.error("Cant re-attach. Error : {}".format(exc.strerror))
        self._control_taken = False
        logging.debug("USB device released, VID={}, PID={}".format(
            hex(self._controller.vendor_id), hex(self._controller.product_id))) 
Example #3
Source File: apihooks.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def reported_access(self, address):
        """Determines if the address should be reported.

        This assesses the destination address for suspiciousness. For example if
        the address resides in a VAD region which is not mapped by a dll then it
        might be suspicious.
        """
        destination_names = self.session.address_resolver.format_address(
            address)

        # For now very simple: If any of the destination_names start with vad_*
        # it means that the address resolver cant determine which module they
        # came from.
        destination = hex(address)
        for destination in destination_names:
            if not destination.startswith("vad_"):
                return False

        return destination 
Example #4
Source File: ssl_context.py    From aerospike-admin with Apache License 2.0 6 votes vote down vote up
def _cert_crl_check(self, cert):
        if not cert:
            raise ValueError(
                "empty or no Server Certificate chain for CRL check")
        if not self._crl_checklist:
            return
        try:
            serial_number = cert.get_serial_number()
            if serial_number is None:
                raise Exception("Wrong Server Certificate: No Serial Number.")
        except Exception:
            raise Exception(
                "Wrong Server Certificate: not able to extract Serial Number.")

        try:
            serial_number_int = int(serial_number)
        except Exception:
            raise Exception(
                "Wrong Server Certificate: not able to extract Serial Number in integer format.")
        if serial_number in self._crl_checklist:
            raise Exception("Server Certificate is in revoked list: (Serial Number: %s)" % (
                str(hex(serial_number_int)))) 
Example #5
Source File: backend.py    From neon with Apache License 2.0 5 votes vote down vote up
def _pretty_print(node):
        operators = {'add': '+',
                     'sub': '-',
                     'mul': '*',
                     'div': '/',
                     'pow': '**'}
        s = ''
        if isinstance(node, Tensor):
            if node.name:
                s = node.name
            else:
                s = 'tensor-' + hex(id(node))
        elif isinstance(node, OpTreeNode):
            if node[2]:
                s += OpTreeNode._pretty_print(node[1]) + ' '
                if node[0]['op'] in operators:
                    s += operators[node[0]['op']]
                else:
                    s += node[0]['op']
                s += ' ' + OpTreeNode._pretty_print(node[2])
            else:
                s = node[0]['op'] + ' ' + OpTreeNode._pretty_print(node[1])
            s = '(' + s + ')'
        else:
            s = str(node)  # TODO
            s = '(' + s + ')'
        return s 
Example #6
Source File: DisasmViewMode.py    From dcc with Apache License 2.0 5 votes vote down vote up
def _drawRow(self, qp, cemu, row, asm, offset=-1):
        log.debug('DRAW AN INSTRUCTION %s %s %s %s %s', asm, row, asm.get_name(), len(asm.get_operands(offset)), hex(self.getPageOffset()))

        qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))

        hex_data = asm.get_hex()

        # write hexdump
        cemu.writeAt(0, row, hex_data)

        # fill with spaces
        cemu.write((MNEMONIC_COLUMN - len(hex_data)) * ' ')

        # let's color some branch instr
        # if asm.isBranch():
        #    qp.setPen(QtGui.QPen(QtGui.QColor(255, 80, 0)))
        # else:
        qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))

        mnemonic = asm.get_name()
        cemu.write(mnemonic)

        # leave some spaces
        cemu.write((MNEMONIC_WIDTH - len(mnemonic)) * ' ')

        if asm.get_symbol():
            qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))
            cemu.write_c('[')

            qp.setPen(QtGui.QPen(QtGui.QColor('yellow'), 1, QtCore.Qt.SolidLine))
            cemu.write(asm.get_symbol())

            qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))
            cemu.write_c(']')

        self._write_operands(asm, qp, cemu, offset)
        self._write_comments(asm, qp, cemu, offset) 
Example #7
Source File: repr.py    From pycrate with GNU Lesser General Public License v2.1 5 votes vote down vote up
def hex(obj):
    if isinstance(obj, Element):
        return obj.hex()
    elif hasattr(obj, '__hex__') and callable(obj.__hex__):
        return obj.__hex__()
    else:
        # will certainly raise
        return builtins.hex(obj) 
Example #8
Source File: core.py    From pythonflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, length=None, graph=None, name=None, dependencies=None, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.length = length
        self.graph = Graph.get_active_graph(graph)
        # Choose a name for the operation and add the operation to the graph
        self._name = None
        self.name = name or uuid.uuid4().hex
        # Get a list of all dependencies relevant to this operation
        self.dependencies = [] if dependencies is None else dependencies
        self.dependencies.extend(self.graph.dependencies)
        # Get the stack context so we can report where the operation was defined
        self._stack = traceback.extract_stack() 
Example #9
Source File: rock_model.py    From POMDPy with MIT License 5 votes vote down vote up
def disp_cell(rs_cell_type):
        if rs_cell_type >= RSCellType.ROCK:
            print(hex(rs_cell_type - RSCellType.ROCK), end=' ')
            return

        if rs_cell_type is RSCellType.EMPTY:
            print(' . ', end=' ')
        elif rs_cell_type is RSCellType.GOAL:
            print('G', end=' ')
        elif rs_cell_type is RSCellType.OBSTACLE:
            print('X', end=' ')
        else:
            print('ERROR-', end=' ')
            print(rs_cell_type, end=' ') 
Example #10
Source File: rawutil.py    From 3DSkit with GNU General Public License v3.0 5 votes vote down vote up
def hex(val, align=0):
	if isinstance(val, int):
		return builtins.hex(val).lstrip('0x').zfill(align)
	else:
		return binascii.hexlify(bytes(val)).decode('ascii').zfill(align) 
Example #11
Source File: rsa.py    From CryptoAttacks with MIT License 5 votes vote down vote up
def print_texts(self):
        print("key {} texts:".format(self.identifier))
        for pair in self.texts:
            if 'cipher' in pair:
                print("Ciphertext: {}".format(hex(pair['cipher'])), end=", ")
            else:
                print("Ciphertext: null", end=", ")
            if 'plain' in pair:
                print("Plaintext: {} (\"{}\")".format(hex(pair['plain']), i2b(pair['plain'], size=self.size)))
            else:
                print("Plaintext: null") 
Example #12
Source File: DataSearch.py    From qtpandas with MIT License 5 votes vote down vote up
def __repr__(self):
        unformatted = "DataSearch({}): {} ({})"
        formatted_string = unformatted.format(hex(id(self)),
                                              self.name,
                                              self._filterString)
        if python_version < 3:
            formatted_string = unformatted.encode("utf-8")

        return formatted_string 
Example #13
Source File: TestApp.py    From qtpandas with MIT License 5 votes vote down vote up
def processDataDrops(self, mimeData):
        """if you have more complicated stuff to do and you want to match some models, might be possible like that"""
        mimeDataPayload = mimeData.data()
        if isinstance(mimeDataPayload, PandasCellPayload):
            if self.dataModel is not None:
                if hex(id(self.dataModel)) == mimeDataPayload.parentId:
                    self.dropWidget.setText("complex stuff done after drop event. {0}".format(mimeDataPayload.column)) 
Example #14
Source File: notifications.py    From RAFCON with Eclipse Public License 1.0 5 votes vote down vote up
def node_name(node):
    return "{class_name} ({id})".format(class_name=node.__class__.__name__, id=hex(id(node))) 
Example #15
Source File: ip.py    From PayloadsAllTheThings with MIT License 5 votes vote down vote up
def HEX_SINGLE(NUMBER,ADD0X):
	if ADD0X == "yes":
		return str(hex(int(NUMBER)))
	else:
		return str(hex(int(NUMBER))).replace("0x","") 
Example #16
Source File: helpers.py    From panoptes with Apache License 2.0 5 votes vote down vote up
def transform_dotted_decimal_to_mac(dotted_decimal_mac):
    """
    Method to transform dotted decimals to Mac address
    Args:
        dotted_decimal_mac(string): dotted decimal string
    Returns:
        mac_address(string): Mac address separated by colon
    """

    decimal_mac = dotted_decimal_mac.split(u'.')
    hex_mac = u':'.join(str(hex(int(i)).lstrip(u'0x')).zfill(2) for i in decimal_mac).upper()
    return hex_mac 
Example #17
Source File: base_objects.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def render_row(self, item, **options):
        return text.Cell(hex(item), align="r") 
Example #18
Source File: clipboard.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def collect(self):
        for session, wndsta, clip, handle in self.calculate():
            # If no tagCLIP is provided, we do not know the format
            if not clip:
                fmt = obj.NoneObject("Format unknown")
            else:
                # Try to get the format name, but failing that, print
                # the format number in hex instead.
                if clip.fmt.v() in constants.CLIPBOARD_FORMAT_ENUM:
                    fmt = str(clip.fmt)
                else:
                    fmt = hex(clip.fmt.v())

            # Try to get the handle from tagCLIP first, but
            # fall back to using _HANDLEENTRY.phead. Note: this can
            # be a value like DUMMY_TEXT_HANDLE (1) etc.
            handle_value = clip.hData or handle.phead.h

            clip_data = ""
            if handle and "TEXT" in fmt:
                clip_data = handle.reference_object().as_string(fmt)

            print(handle)

            yield dict(session=session.SessionId,
                       window_station=wndsta.Name,
                       format=fmt,
                       handle=handle_value,
                       object=handle.phead.v(),
                       data=clip_data,
                       hexdump=handle.reference_object().as_hex()) 
Example #19
Source File: cmdpacket.py    From alienfx with GNU General Public License v3.0 5 votes vote down vote up
def _parse_cmd_set_speed(self, args):
        """ Parse a packet containing the "set speed" command and 
        return it as a human readable string.
        """
        pkt = args["pkt"]
        return "SET_SPEED: {}".format(hex((pkt[2] << 8) + pkt[3]))
            
    # @classmethod 
Example #20
Source File: cmdpacket.py    From alienfx with GNU General Public License v3.0 5 votes vote down vote up
def _unpack_colour(self, pkt):
        """ Unpack a colour value from the given packet and return it as a
        3-member tuple

        TODO: This too might need improvement for newer controllers
        """
        red = hex(pkt[0] >> 4)
        green = hex(pkt[0] & 0xf)
        blue = hex(pkt[1] >> 4)
        return (red, green, blue) 
Example #21
Source File: cmdpacket.py    From alienfx with GNU General Public License v3.0 5 votes vote down vote up
def _unpack_colour_pair(self, pkt):
        """ Unpack two colour values from the given packet and return them as a
        list of two tuples (each colour is a 3-member tuple)

        TODO: This might need improvement for newer controllers...
        """ 
        red1 = hex(pkt[0] >> 4)
        green1 = hex(pkt[0] & 0xf)
        blue1 = hex(pkt[1] >> 4)
        red2 = hex(pkt[1] & 0xf)
        green2 = hex(pkt[2] >> 4)
        blue2 = hex(pkt[2] & 0xf)
        return [(red1, green1, blue1), (red2, green2, blue2)] 
Example #22
Source File: usbdriver.py    From alienfx with GNU General Public License v3.0 5 votes vote down vote up
def acquire(self):
        """ Acquire control from libusb of the AlienFX controller."""
        if self._control_taken:
            return
        self._dev = usb.core.find(
            idVendor=self._controller.vendor_id, 
            idProduct=self._controller.product_id)
        if (self._dev is None):
            msg = "ERROR: No AlienFX USB controller found; tried "
            msg += "VID {}".format(self._controller.vendor_id)
            msg += ", PID {}".format(self._controller.product_id)
            logging.error(msg)
        try:
            self._dev.detach_kernel_driver(0)
        except USBError as exc: 
            logging.error(
                "Cant detach kernel driver. Error : {}".format(exc.strerror))
        try:
            self._dev.set_configuration()
        except USBError as exc: 
            logging.error(
                "Cant set configuration. Error : {}".format(exc.strerror))
        try:
            usb.util.claim_interface(self._dev, 0)
        except USBError as exc: 
            logging.error(
                "Cant claim interface. Error : {}".format(exc.strerror))
        self._control_taken = True
        logging.debug("USB device acquired, VID={}, PID={}".format(
            hex(self._controller.vendor_id), hex(self._controller.product_id))) 
Example #23
Source File: HexViewMode.py    From dcc with Apache License 2.0 5 votes vote down vote up
def setSize(self, size):
        self._size = size
        self.setText(self.ID_SIZE, hex(size)) 
Example #24
Source File: HexViewMode.py    From dcc with Apache License 2.0 5 votes vote down vote up
def setOffset(self, offset):
        self._offset = offset
        self.setText(self.ID_OFFSET, hex(offset)) 
Example #25
Source File: HexViewMode.py    From dcc with Apache License 2.0 5 votes vote down vote up
def drawCursor(self, qp):
        qp.setBrush(QtGui.QColor(255, 255, 0))
        if self.isInEditMode():
            qp.setBrush(QtGui.QColor(255, 102, 179))

        cursorX, cursorY = self.cursor.getPosition()

        columns = self.HexColumns[self.idxHexColumns]
        if cursorX > columns:
            self.cursor.moveAbsolute(columns - 1, cursorY)

        # get cursor position again, maybe it was moved
        cursorX, cursorY = self.cursor.getPosition()

        qp.setOpacity(0.8)
        if self.isInEditMode():
            qp.setOpacity(0.5)
        # cursor on text
        qp.drawRect((self.COLUMNS * 3 + self.gap + cursorX) * self.fontWidth, cursorY * self.fontHeight + 2,
                    self.fontWidth, self.fontHeight)

        # cursor on hex
        if not self.isInEditMode():
            qp.drawRect(cursorX * 3 * self.fontWidth, cursorY * self.fontHeight + 2, 2 * self.fontWidth,
                        self.fontHeight)
        else:
            if self.highpart:
                qp.drawRect(cursorX * 3 * self.fontWidth, cursorY * self.fontHeight + 2, 1 * self.fontWidth,
                            self.fontHeight)
            else:
                qp.drawRect(cursorX * 3 * self.fontWidth + self.fontWidth, cursorY * self.fontHeight + 2,
                            1 * self.fontWidth, self.fontHeight)

        qp.setOpacity(1) 
Example #26
Source File: HexViewMode.py    From dcc with Apache License 2.0 4 votes vote down vote up
def drawTextMode(self, qp, row=0, howMany=1):

        # draw background
        qp.fillRect(0, row * self.fontHeight, self.CON_COLUMNS * self.fontWidth,
                    howMany * self.fontHeight + self.SPACER, self.backgroundBrush)

        # set text pen&font
        qp.setFont(self.font)
        qp.setPen(self.textPen)

        cemu = ConsoleEmulator(qp, self.ROWS, self.CON_COLUMNS)

        page = self.transformationEngine.decorate()

        cemu.gotoXY(0, row)

        for i, c in enumerate(self.getDisplayablePage()[row * self.COLUMNS:(
            row + howMany) * self.COLUMNS]):  # TODO: does not apply all decorators

            w = i + row * self.COLUMNS

            if (w + 1) % self.COLUMNS == 0:
                hex_s = str(hex(c)[2:]).zfill(2)
            else:
                hex_s = str(hex(c)[2:]).zfill(2) + ' '

            qp.setPen(self.transformationEngine.choosePen(w))

            if self.transformationEngine.chooseBrush(w) is not None:
                qp.setBackgroundMode(1)
                qp.setBackground(self.transformationEngine.chooseBrush(w))

            # write hex representation
            cemu.write(hex_s, noBackgroudOnSpaces=True)
            # save hex position
            x, y = cemu.getXY()
            # write text
            cemu.writeAt(self.COLUMNS * 3 + self.gap + (w % self.COLUMNS), y, self.cp437(c))
            # go back to hex chars
            cemu.gotoXY(x, y)
            if (w + 1) % self.COLUMNS == 0:
                cemu.writeLn()

            qp.setBackgroundMode(0)