Will unpack the received text. Depending on the context the original
         response may have been transformed before transmission.
        :param txt:
        :param binding:
        :param msgtype:
        :return:
498471
def unravel(txt, binding, msgtype="response"):
        
        # logger.debug("unravel '%s'", txt)
        if binding not in [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST,
                           BINDING_SOAP, BINDING_URI, BINDING_HTTP_ARTIFACT,
                           None]:
            raise UnknownBinding("Don't know how to handle '%s'" % binding)
        else:
            try:
                if binding == BINDING_HTTP_REDIRECT:
                    xmlstr = decode_base64_and_inflate(txt)
                elif binding == BINDING_HTTP_POST:
                    xmlstr = base64.b64decode(txt)
                elif binding == BINDING_SOAP:
                    func = getattr(soap,
                                   "parse_soap_enveloped_saml_%s" % msgtype)
                    xmlstr = func(txt)
                elif binding == BINDING_HTTP_ARTIFACT:
                    xmlstr = base64.b64decode(txt)
                else:
                    xmlstr = txt
            except Exception:
                raise UnravelError("Unravelling binding '%s' failed" % binding)

        return xmlstr
819528
def on_btn_unpack(self, event):
        
        dlg = wx.FileDialog(
            None, message = "choose txt file to unpack",
            defaultDir=self.WD,
            defaultFile="",
            style=wx.FD_OPEN #| wx.FD_CHANGE_DIR
            )
        if dlg.ShowModal() == wx.ID_OK:
            FILE = dlg.GetPath()
            input_dir, f = os.path.split(FILE)
        else:
            return False

        outstring="download_magic.py -f {} -WD {} -ID {} -DM {}".format(f, self.WD, input_dir, self.data_model_num)

        # run as module:
        print("-I- running python script:\n %s"%(outstring))
        wait = wx.BusyInfo("Please wait, working...")
        wx.SafeYield()
        ex = None
        try:
            if ipmag.download_magic(f, self.WD, input_dir, overwrite=True, data_model=self.data_model):
                text = "Successfully ran download_magic.py program.\nMagIC files were saved in your working directory.\nSee Terminal/message window for details."
            else:
                text = "Something went wrong.  Make sure you chose a valid file downloaded from the MagIC database and try again."

        except Exception as ex:
            text = "Something went wrong.  Make sure you chose a valid file downloaded from the MagIC database and try again."
            del wait
            dlg = wx.MessageDialog(self, caption="Saved", message=text, style=wx.OK)
            result = dlg.ShowModal()
            if result == wx.ID_OK:
                dlg.Destroy()
            if ex:
                raise(ex)
        self.contribution = cb.Contribution(self.WD)
1061119
def unpack(self, fmt):
        

        sfmt = compile_struct(fmt)
        size = sfmt.size

        offset = self.offset
        if self.data:
            avail = len(self.data) - offset
        else:
            avail = 0

        if avail < size:
            raise UnpackException(fmt, size, avail)

        self.offset = offset + size
        return sfmt.unpack_from(self.data, offset)
214032
def pgettext(self, context, string, domain=None, **variables):
        """"""
        t = self.get_translations(domain)
        return t.upgettext(context, string) % variables
955589
def text_to_data(self, text, elt, ps):
        '''
        '''
        if self.strip: text = text.strip()
        if self.pyclass is not None:
            return self.pyclass(text.encode(UNICODE_ENCODING))
        return text.encode(UNICODE_ENCODING)
201205
def to_text(s, encoding="utf-8"):
    
    if isinstance(s, six.text_type):
        return s
    else:
        return six.binary_type(s).decode(encoding)
752817
def parse_text(self, formatted_text):
        
        assert isinstance(formatted_text, FormattedText)
        ret_val = []
        fmt = formatted_text.fmt if self._prev_fmt_closed else self._prev_fmt
        fmt = QtGui.QTextCharFormat(fmt)
        if not self._pending_text:
            stripped_text = formatted_text.txt
        else:
            stripped_text = self._pending_text + formatted_text.txt
            self._pending_text = ''
        while stripped_text:
            try:
                escape_pos = stripped_text.index(self._escape[0])
            except ValueError:
                ret_val.append(Operation('draw', FormattedText(stripped_text, fmt)))
                break
            else:
                if escape_pos != 0:
                    ret_val.append(Operation('draw', FormattedText(stripped_text[:escape_pos], fmt)))
                    stripped_text = stripped_text[escape_pos:]
                    fmt = QtGui.QTextCharFormat(fmt)
            assert stripped_text[0] == self._escape[0]
            while stripped_text and stripped_text[0] == self._escape[0]:
                if self._escape.startswith(stripped_text):
                    # control sequence not complete
                    self._pending_text += stripped_text
                    stripped_text = ''
                    break
                if not stripped_text.startswith(self._escape):
                    # check vt100 escape sequences
                    ctrl_seq = False
                    for alt_seq in self._escape_alts:
                        if stripped_text.startswith(alt_seq):
                            ctrl_seq = True
                            break
                    if not ctrl_seq:
                        # not a control sequence
                        self._pending_text = ''
                        ret_val.append(Operation('draw', FormattedText(stripped_text[:1], fmt)))
                        fmt = QtGui.QTextCharFormat(fmt)
                        stripped_text = stripped_text[1:]
                        continue
                self._pending_text += _mid(stripped_text, 0, self._escape_len)
                stripped_text = stripped_text[self._escape_len:]

                # Non draw related command (cursor/erase)
                if self._pending_text in [self._escape] + self._escape_alts:
                    m = self._supported_commands.match(stripped_text)
                    if m and self._pending_text == self._escape:
                        _, e = m.span()
                        n = m.group('n')
                        cmd = m.group('cmd')
                        if not n:
                            n = 0
                        ret_val.append(Operation(self._commands[cmd], n))
                        self._pending_text = ''
                        stripped_text = stripped_text[e:]
                        continue
                    else:
                        m = self._unsupported_command.match(stripped_text)
                        if m:
                            self._pending_text = ''
                            stripped_text = stripped_text[m.span()[1]:]
                            continue
                        elif self._pending_text in ['\x1b=', '\x1b>']:
                            self._pending_text = ''
                            continue

                # Handle Select Graphic Rendition commands
                # get the number
                str_nbr = ''
                numbers = []
                while stripped_text:
                    if stripped_text[0].isdigit():
                        str_nbr += stripped_text[0]
                    else:
                        if str_nbr:
                            numbers.append(str_nbr)
                        if not str_nbr or stripped_text[0] != self._semicolon:
                            break
                        str_nbr = ''
                    self._pending_text += _mid(stripped_text, 0, 1)
                    stripped_text = stripped_text[1:]

                if not stripped_text:
                    break

                # remove terminating char
                if not stripped_text.startswith(self._color_terminator):
                    # _logger().warn('removing %s', repr(self._pending_text + stripped_text[0]))
                    self._pending_text = ''
                    stripped_text = stripped_text[1:]
                    break

                # got consistent control sequence, ok to clear pending text
                self._pending_text = ''
                stripped_text = stripped_text[1:]

                if not numbers:
                    fmt = QtGui.QTextCharFormat(formatted_text.fmt)
                    self.end_format_scope()

                i_offset = 0
                n = len(numbers)
                for i in range(n):
                    i += i_offset
                    code = int(numbers[i])

                    if self._TextColorStart <= code <= self._TextColorEnd:
                        fmt.setForeground(_ansi_color(code - self._TextColorStart, self.color_scheme))
                        self._set_format_scope(fmt)
                    elif self._BackgroundColorStart <= code <= self._BackgroundColorEnd:
                        fmt.setBackground(_ansi_color(code - self._BackgroundColorStart, self.color_scheme))
                        self._set_format_scope(fmt)
                    else:
                        if code == self._ResetFormat:
                            fmt = QtGui.QTextCharFormat(formatted_text.fmt)
                            self.end_format_scope()
                        elif code == self._BoldText:
                            fmt.setFontWeight(QtGui.QFont.Bold)
                            self._set_format_scope(fmt)
                        elif code == self._NotBold:
                            fmt.setFontWeight(QtGui.QFont.Normal)
                            self._set_format_scope(fmt)
                        elif code == self._ItalicText:
                            fmt.setFontItalic(True)
                            self._set_format_scope(fmt)
                        elif code == self._NotItalicNotFraktur:
                            fmt.setFontItalic(False)
                            self._set_format_scope(fmt)
                        elif code == self._UnderlinedText:
                            fmt.setUnderlineStyle(fmt.SingleUnderline)
                            fmt.setUnderlineColor(fmt.foreground().color())
                            self._set_format_scope(fmt)
                        elif code == self._NotUnderlined:
                            fmt.setUnderlineStyle(fmt.NoUnderline)
                            self._set_format_scope(fmt)
                        elif code == self._DefaultTextColor:
                            fmt.setForeground(formatted_text.fmt.foreground())
                            self._set_format_scope(fmt)
                        elif code == self._DefaultBackgroundColor:
                            fmt.setBackground(formatted_text.fmt.background())
                            self._set_format_scope(fmt)
                        elif code == self._Dim:
                            fmt = QtGui.QTextCharFormat(fmt)
                            fmt.setForeground(fmt.foreground().color().darker(self.DIM_FACTOR))
                        elif code == self._Negative:
                            normal_fmt = fmt
                            fmt = QtGui.QTextCharFormat(fmt)
                            fmt.setForeground(normal_fmt.background())
                            fmt.setBackground(normal_fmt.foreground())
                        elif code == self._Positive:
                            fmt = QtGui.QTextCharFormat(formatted_text.fmt)
                        elif code in [self._RgbBackgroundColor, self._RgbTextColor]:
                            # See http://en.wikipedia.org/wiki/ANSI_escape_code#Colors
                            i += 1
                            if i == n:
                                break
                            next_code = int(numbers[i])
                            if next_code == 2:
                                # RGB set with format: 38;2;<r>;<g>;<b>
                                if i + 3 < n:
                                    method = fmt.setForeground if code == self._RgbTextColor else fmt.setBackground
                                    method(QtGui.QColor(int(numbers[i + 1]), int(numbers[i + 2]), int(numbers[i + 3])))
                                    self._set_format_scope(fmt)
                                i_offset = 3
                            elif next_code == 5:
                                # 256 color mode with format: 38;5;<i>
                                index = int(numbers[i + 1])
                                if index < 8:
                                    # The first 8 colors are standard low-intensity ANSI colors.
                                    color = _ansi_color(index, self.color_scheme)
                                elif index < 16:
                                    # The next 8 colors are standard high-intensity ANSI colors.
                                    color = _ansi_color(index - 8, self.color_scheme).lighter(150)
                                elif index < 232:
                                    # The next 216 colors are a 6x6x6 RGB cube.
                                    o = index - 16
                                    color = QtGui.QColor((o / 36) * 51, ((o / 6) % 6) * 51, (o % 6) * 51)
                                else:
                                    # The last 24 colors are a greyscale gradient.
                                    grey = (index - 232) * 11
                                    color = QtGui.QColor(grey, grey, grey)

                                if code == self._RgbTextColor:
                                    fmt.setForeground(color)
                                else:
                                    fmt.setBackground(color)

                                self._set_format_scope(fmt)
                        else:
                            _logger().warn('unsupported SGR code: %r', code)
        return ret_val
318036
def _pack(self, msg_type, payload):
        
        pb = payload.encode('utf-8')
        s = struct.pack('=II', len(pb), msg_type.value)
        return self.MAGIC.encode('utf-8') + s + pb
461384
def decode_sent_msg(pref, message, pretty=False):
    
    newline = "\n" if pretty else " "
    indent = "    " if pretty else ""
    start = newline + indent

    out = []
    out.append("%s%s{%sSEQNUM: %d," % (pref, newline, start, message[Const.W_SEQ]))
    out.append("%sCOMPRESSION: %d," % (start, message[Const.W_COMPRESSION]))
    out.append("%sHASH: %s...," % (start, str(binascii.b2a_hex(message[Const.W_HASH]).decode('ascii'))[:10]))
    out.append("%sMESSAGE:%s{%sCLIENTREF: %s," % (start, start, start + indent,
                                                  message[Const.W_MESSAGE][Const.M_CLIENTREF]))
    out.append("%sRESOURCE: %s," % (start + indent, R_TYPES[message[Const.W_MESSAGE][Const.M_RESOURCE]]))
    out.append("%sTYPE: %s," % (start + indent, C_TYPES[message[Const.W_MESSAGE][Const.M_TYPE]]))
    out.append("%sACTION: %s," % (start + indent, message[Const.W_MESSAGE][Const.M_ACTION]))
    if Const.M_RANGE in message[Const.W_MESSAGE]:
        out.append("%sRANGE: %s," % (start + indent, message[Const.W_MESSAGE][Const.M_RANGE]))
    out.append("%sPAYLOAD: %s%s}%s}" % (start + indent, message[Const.W_MESSAGE][Const.M_PAYLOAD], start, newline))

    return ''.join(out)
524401
def unpack(packed, object_hook=decode,
           list_hook=None, use_list=False, encoding='utf-8',
           unicode_errors='strict', object_pairs_hook=None,
           max_buffer_size=0, ext_hook=ExtType):
    

    return Unpacker(packed, object_hook=object_hook,
                    list_hook=list_hook,
                    use_list=use_list, encoding=encoding,
                    unicode_errors=unicode_errors,
                    object_pairs_hook=object_pairs_hook,
                    max_buffer_size=max_buffer_size,
                    ext_hook=ext_hook)
623361
def of_text(self, text, encoding="utf-8"):
        
        m = self.hash_algo()
        m.update(text.encode(encoding))
        return self.digest(m)
1371511
def text_result(text: str,
                extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,
                filename: str = None) -> WSGI_TUPLE_TYPE:
    
    extraheaders = extraheaders or []
    if filename:
        extraheaders.append(
            ('content-disposition', 'inline; filename="{}"'.format(filename))
        )
    contenttype = 'text/plain; charset=utf-8'
    if filename:
        contenttype += '; filename="{}"'.format(filename)
    return contenttype, extraheaders, text.encode("utf-8")
272965
def ungettext(self):
        
        # pylint: disable=no-member
        if six.PY2:
            return self._translations.ungettext
        else:
            return self._translations.ngettext
1348707
def unescape(msg, extra_format_dict={}):
    """"""
    new_msg = ''

    extra_format_dict.update(format_dict)

    while len(msg):
        char = msg[0]
        msg = msg[1:]
        if char == escape_character:
            escape_key = msg[0]
            msg = msg[1:]

            # we handle this character separately, otherwise we mess up and
            #   double escape characters while escaping and unescaping
            if escape_key == escape_character:
                new_msg += escape_character

            elif escape_key == '{':
                buf = ''
                new_char = ''
                while True:
                    new_char = msg[0]
                    msg = msg[1:]

                    if new_char == '}':
                        break
                    else:
                        buf += new_char

                new_msg += _get_from_format_dict(extra_format_dict, buf)

            else:
                new_msg += _get_from_format_dict(extra_format_dict, escape_key)

            if escape_key == 'c':
                fill_last = len(msg) and msg[0] in digits
                colours, msg = extract_girc_colours(msg, fill_last)
                new_msg += colours
        else:
            new_msg += char

    return new_msg
1361362
def deserialize(cls, v, bind_client=None):
        
        if v is None:
            return None
        o = cls(bind_client=bind_client)
        o.from_dict(v)
        return o
714160
def fmtstr(string, *args, **kwargs):
    # type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr
    
    atts = parse_args(args, kwargs)
    if isinstance(string, FmtStr):
        pass
    elif isinstance(string, (bytes, unicode)):
        string = FmtStr.from_str(string)
    else:
        raise ValueError("Bad Args: %r (of type %s), %r, %r" % (string, type(string), args, kwargs))
    return string.copy_with_new_atts(**atts)
751773
def xgettext(self, template):
        """"""

        cmd = 'xgettext -d django -L Python --keyword=gettext_noop \
            --keyword=gettext_lazy --keyword=ngettext_lazy:1,2 --from-code=UTF-8 \
            --output=- -'

        p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (msg, err) = p.communicate(input=templatize(template))

        if err:
            # dont raise exception, some stuff in stderr are just warmings
            logging.warning(err)

        if XGETTEXT_REENCODES_UTF8:
            return msg.decode('utf-8').encode('iso-8859-1')

        return msg