Takes a text message and return a tuple
348801
def to_bytes(val):
    
    if val is NoResponse:
        return val
    val = val.replace('\\r', '\r').replace('\\n', '\n')
    return val.encode()
1272034
def tuplecount(text):
    ''''''
    worddict = wordcount(text)
    countlist = []
    for key in worddict.keys():
        countlist.append((key,worddict[key]))
    countlist = list(reversed(sorted(countlist,key = lambda x: x[1])))
    return countlist
690678
def text(self) -> bytes:
        """"""
        if self.condition:
            if self.code:
                return BytesFormat(b'%b %b %b') \
                    % (self.condition, self.code, self._text)
            else:
                return BytesFormat(b'%b %b') % (self.condition, self._text)
        else:
            return bytes(self._text)
1337942
def ParseFromString(self, text, message):
    """"""
    if not isinstance(text, str):
      text = text.decode('utf-8')
    return self.ParseLines(text.split('\n'), message)
966218
def get_mime_message(subject, text):
    
    message = MIMEText(
        "<html>" +
        str(text).replace("\n", "<br>") +
        "</html>", "html"
    )
    message["subject"] = str(subject)
    return message
43319
def to_text(self):
        
        if self.text is None:
            return
        else:
            text = ''
            for t in self.text:
                text += t.to_text() + ' '
            return ' '.join(text.split())
1275552
def from_text(text):
    

    if text.isdigit():
        total = long(text)
    else:
        if not text[0].isdigit():
            raise BadTTL
        total = 0L
        current = 0L
        for c in text:
            if c.isdigit():
                current *= 10
                current += long(c)
            else:
                c = c.lower()
                if c == 'w':
                    total += current * 604800L
                elif c == 'd':
                    total += current * 86400L
                elif c == 'h':
                    total += current * 3600L
                elif c == 'm':
                    total += current * 60L
                elif c == 's':
                    total += current
                else:
                    raise BadTTL("unknown unit '%s'" % c)
                current = 0
        if not current == 0:
            raise BadTTL("trailing integer")
    if total < 0L or total > 2147483647L:
        raise BadTTL("TTL should be between 0 and 2^31 - 1 (inclusive)")
    return total
646759
def batch_message_from_parts(cls, messages):
        '''
        '''
        # Comma-separate the messages and wrap the lot in square brackets
        middle = b', '.join(messages)
        if not middle:
            raise ProtocolError.empty_batch()
        return b''.join([b'[', middle, b']'])
964647
def str2listtuple(self, string_message):
        ""

        if type(string_message).__name__ not in ('str', 'unicode'):
            raise TypeError("Must provide a string or unicode")

        if not string_message.endswith('\n'):
            string_message += "\n"

        tpl_list = []
        for line in string_message.split('\n'):
            line = line.strip()
            if not line:
                continue
            path, metric, timestamp = (None, None, None)
            try:
                (path, metric, timestamp) = line.split()
            except ValueError:
                raise ValueError(
                    "message must contain - metric_name, value and timestamp '%s'"
                    % line)
            try:
                timestamp = float(timestamp)
            except ValueError:
                raise ValueError("Timestamp must be float or int")

            tpl_list.append((path, (timestamp, metric)))

        if len(tpl_list) == 0:
            raise GraphiteSendException("No messages to send")

        payload = pickle.dumps(tpl_list)
        header = struct.pack("!L", len(payload))
        message = header + payload

        return message
279265
def text(value, encoding="utf-8", errors="strict"):
    """"""
    if isinstance(value, text_type):
        return value
    elif isinstance(value, bytes):
        return text_type(value, encoding, errors)
    else:
        return text_type(value)
1144190
def _structure_tuple(self, obj, tup):
        """"""
        tup_params = tup.__args__
        has_ellipsis = tup_params and tup_params[-1] is Ellipsis
        if tup_params is None or (has_ellipsis and tup_params[0] is Any):
            # Just a Tuple. (No generic information.)
            return tuple(obj)
        if has_ellipsis:
            # We're dealing with a homogenous tuple, Tuple[int, ...]
            tup_type = tup_params[0]
            conv = self._structure_func.dispatch(tup_type)
            return tuple(conv(e, tup_type) for e in obj)
        else:
            # We're dealing with a heterogenous tuple.
            return tuple(
                self._structure_func.dispatch(t)(e, t)
                for t, e in zip(tup_params, obj)
            )
751742
def text_to_data(self, text, elt, ps):
        '''
        '''
        if text is None:
            return None
        
        m = self.lex_pattern.match(text)
        if not m:
            raise EvaluateException('Bad Gregorian: %s' %text, ps.Backtrace(elt))
        try:
            retval = _dict_to_tuple(m.groupdict())
        except ValueError, e:
            #raise EvaluateException(str(e))
            raise
        
        if self.pyclass is not None:
            return self.pyclass(retval)
        return retval
720581
def from_Message(cls, kmsg):
        
        return cls(
            uuid=kmsg.uuid, params=kmsg.params, result=kmsg.result,
            metadata=kmsg.metadata
        )
709561
def _wrap_data(data: Union[str, bytes]):
        
        MsgType = TextMessage if isinstance(data, str) else BytesMessage
        return MsgType(data=data, frame_finished=True, message_finished=True)
519041
def fetch_email(M, msg_id):
    """"""
    res, data = M.fetch(msg_id, '(RFC822)')
    if res == 'OK':
        # Data here is a list with 1 element containing a tuple
        # whose 2nd element is a long string containing the email
        # The content is a bytes that must be decoded
        raw_msg_txt = data[0][1]
        # In Python3, we call message_from_bytes, but this function doesn't
        # exist in Python 2.
        try:
            msg = email.message_from_bytes(raw_msg_txt)
        except AttributeError:
            msg = email.message_from_string(raw_msg_txt)
        # At this point, we have a message containing bytes (not unicode)
        # fields that will still need to be decoded, ideally according to the
        # character set specified in the message.
        return msg
    else:
        return None
696625
def send(self, messages):
        """"""

        tmpSms = SMS(to='', message='')
        if str(type(messages)) == str(type(tmpSms)):
            messages = [messages]

        xml_root = self.__init_xml('Message')
        wrapper_id = 0

        for m in messages:
            m.wrapper_id = wrapper_id
            msg = self.__build_sms_data(m)
            sms = etree.SubElement(xml_root, 'SMS')
            for sms_element in msg:
                element = etree.SubElement(sms, sms_element)
                element.text = msg[sms_element]

        # print etree.tostring(xml_root)
        response = clockwork_http.request(SMS_URL, etree.tostring(xml_root, encoding='utf-8'))
        response_data = response['data']

        # print response_data
        data_etree = etree.fromstring(response_data)

        # Check for general error
        err_desc = data_etree.find('ErrDesc')
        if err_desc is not None:
            raise clockwork_exceptions.ApiException(err_desc.text, data_etree.find('ErrNo').text)

        # Return a consistent object
        results = []
        for sms in data_etree:
            matching_sms = next((s for s in messages if str(s.wrapper_id) == sms.find('WrapperID').text), None)
            new_result = SMSResponse(
                sms = matching_sms,
                id = '' if sms.find('MessageID') is None else sms.find('MessageID').text,
                error_code = 0 if sms.find('ErrNo') is None else sms.find('ErrNo').text,
                error_message = '' if sms.find('ErrDesc') is None else sms.find('ErrDesc').text,
                success = True if sms.find('ErrNo') is None else (sms.find('ErrNo').text == 0)
            )
            results.append(new_result)

        if len(results) > 1:
            return results

        return results[0]
307841
def get_message(self, level, alert, value, **kwargs):
        
        target, ntype = kwargs.get('target'), kwargs.get('ntype')

        msg_type = 'telegram' if ntype == 'graphite' else 'short'
        tmpl = TEMPLATES[ntype][msg_type]
        generated = tmpl.generate(
            level=level, reactor=self.reactor, alert=alert,
            value=value, target=target,)
        return generated.decode().strip()