Пример #1
0
 def __boolOp__(self, other, operation='&'):
     cname = ObjectTypeName.typeClassName(self).split('.')[-1]
     cls = eval(cname)
     if (isinstance(other, cls)):
         value = 0
         if (operation == EnumInstance._boolOp_AND):
             value = self.value & other.value
         elif (operation == EnumInstance._boolOp_OR):
             value = self.value | other.value
         else:
             print_function(
                 '(%s.%s) :: WARNING: Expected operation to be "%s" or "%s" but it is "%s".'
                 % (ObjectTypeName.typeName(self), misc.funcName(),
                    EnumInstance._boolOp_AND, EnumInstance._boolOp_OR,
                    operation))
         names = self.__names__(value)
         e = cls(self.parent, self.classname,
                 EnumInstance._concat_symbol.join(names), value)
         return e
     else:
         print_function(
             '(%s.%s) :: ERROR: Expected other to be of type "%s" but it is of type "%s".'
             % (ObjectTypeName.typeName(self), misc.funcName(),
                ObjectTypeName.typeName(self),
                ObjectTypeName.typeName(other)))
     return None
Пример #2
0
 def fromDict(self, args):
     if (lists.isDict(args)):
         try:
             __iter__ = args.iteritems()
         except:
             try:
                 __iter__ = args.asPythonDict().iteritems()
             except:
                 try:
                     __iter__ = args.asDict().iteritems()
                 except:
                     __iter__ = None
         for ak, av in __iter__:
             try:
                 for k, v in av.iteritems():
                     self.__dict__['%s_%s' % (ak, k)] = v
             except:
                 self.__dict__[ak] = av if (not misc.isList(av)) else [
                     item if
                     (not lists.isDict(item)) else self.__class__(item)
                     for item in av
                 ]
     else:
         logging.warning(
             '(%s.%s) :: Illegal args variable, expected type "dict" but got type "%s".'
             % (ObjectTypeName.typeName(self), misc.funcName(),
                ObjectTypeName.typeName(args)))
Пример #3
0
    def __lazyimport_import(self):

        """ Import the module now.
        """
        # Load and register module
        name = self.__lazyimport_name
        if (self.__lazyimport_loaded):
            return self.__lazyimport_locals[name]
        if (_utils.isBeingDebugged) and (_utils.isVerbose):
            print '%s: Loading module %r' % (ObjectTypeName.typeName(self),name)
        self.__lazyimport_locals[name] \
             = module \
             = __import__(name,
                          self.__lazyimport_locals,
                          self.__lazyimport_globals,
                          '*')

        # Fill namespace with all symbols from original module to
        # provide faster access.
        self.__dict__.update(module.__dict__)

        # Set import flag
        self.__dict__['__lazyimport_loaded'] = 1

        if (_utils.isBeingDebugged) and (_utils.isVerbose):
            print '%s: Module %r loaded' % (ObjectTypeName.typeName(self),name)
        return module
Пример #4
0
def deleteSalesForceObjects(sfdc, list_of_ids):
    import sys, traceback
    from vyperlogix import misc
    from vyperlogix.misc import ObjectTypeName
    deleted_ids = []
    t_sfdc = ObjectTypeName.typeName(sfdc)
    if (t_sfdc.find('.connection.Connection') > -1):
        if (all([misc.isString(id) for id in list_of_ids])):
            try:
                delete_result = sfdc.delete(list_of_ids)
                deleted_ids = sfdc.resultToIdList(delete_result,
                                                  success_status=True)
            except Exception as details:
                exc_info = sys.exc_info()
                info_string = '\n'.join(traceback.format_exception(*exc_info))
                info_string = '%s :: Cannot process, Reason: %s\n%s' % (
                    misc.funcName(), str(details), info_string)
                print >> sys.stderr, info_string
        else:
            info_string = '%s :: Cannot process, Reason: "%s" is not a list of id(s) each being a string.' % (
                misc.funcName(), str(list_of_ids))
            print >> sys.stderr, info_string
    else:
        info_string = '%s :: Cannot process, Reason: "%s" is not a valid connection object to pyax however it appears to be "%s".' % (
            misc.funcName(), str(sfdc), t_sfdc)
        print >> sys.stderr, info_string
    return deleted_ids
Пример #5
0
 def fromDict(self, args):
     if (lists.isDict(args)):
         for ak, av in args.iteritems():
             if (lists.isDict(av)):
                 self.__dict__[ak] = SmartObject(av)
             else:
                 self.__dict__[ak] = av if (not misc.isList(av)) else [
                     item if
                     (not lists.isDict(item)) else self.__class__(item)
                     for item in av
                 ]
     else:
         logging.warning(
             '(%s.%s) :: Illegal args variable, expected type "dict" but got type "%s".'
             % (ObjectTypeName.typeName(self), misc.funcName(),
                ObjectTypeName.typeName(args)))
Пример #6
0
    def __init__(self, logger=None):
        self.__smtp_server__ = ''
        self.__smtp_port__ = -1
        self.__smtp_username__ = ''
        self.__smtp_password__ = ''
        self.__logger__ = None

        print 'You cannot use the %s class because this is an Abstract Class.  Try using one of the sub-classes instead.' % (
            ObjectTypeName.typeName(self))
Пример #7
0
 def __new__(cls, parent, classname, enumname, value):
     self = super(EnumInstance, cls).__new__(cls, str(value))
     self.__parent = parent
     self.__classname = classname
     if (misc.isString(enumname)):
         self.__enumname = enumname
         self.__value = value
     elif (misc.isList(enumname)):
         self.__value = 0
         for n in enumname:
             val = parent[n].value
             self.__value |= val
         assert self.__value == value, '(%s.%s) :: ERROR: Why the freak is the value of "%s" not equal to "%s"; the value that was stated to equate to "%s" cannot be correct according to the actual values from the parent of this %s object.' % (
             ObjectTypeName.typeName(self), misc.funcName(), self.__value,
             value, enumname, ObjectTypeName.typeName(self))
     else:
         print_function(
             '(%s.%s) :: ERROR: What the freak is the meaning of enumname of "%s" of type "%s".'
             % (ObjectTypeName.typeName(self), misc.funcName(), enumname,
                ObjectTypeName.typeName(enumname)))
     return self
Пример #8
0
    def __getattr__(self, name):

        """ Import the module on demand and get the attribute.
        """
        if (self.__lazyimport_loaded):
            raise AttributeError, name
        if (_utils.isBeingDebugged) and (_utils.isVerbose):
            print '%s: Module load triggered by attribute %r read access' % (ObjectTypeName.typeName(self),name)
        module = self.__lazyimport_import()
        try:
            return getattr(module, name)
        except:
            return module
Пример #9
0
 def login(self):
     if (self.smtp_port < 1):
         toks = self.smtp_server.split(':')
         self.smtp_server = toks[0]
         self.smtp_port = -1 if (len(toks) != 2) else -1 if (
             not toks[-1].isdigit()) else int(toks[-1])
     if (len(self.smtp_server) > 0) and (isinstance(
             self.smtp_port, int)) and (self.smtp_port > -1):
         print '(%s.%s) :: smtpServer=[%s], port=[%s], username=[%s], password=[%s]' % (
             ObjectTypeName.typeName(self), misc.funcName(),
             self.smtp_server, self.smtp_port, self.smtp_username,
             self.smtp_password)
         try:
             self.mailServer = smtplib.SMTP(host=self.smtp_server,
                                            port=self.smtp_port)
             self.mailServer.set_debuglevel(self.debug)
             if (len(self.smtp_username) > 0) and (len(self.smtp_password) >
                                                   0):
                 self.mailServer.login(self.smtp_username,
                                       self.smtp_password)
         except Exception as details:
             tbinfofile = StringIO.StringIO()
             traceback.print_exc(None, tbinfofile)
             tbinfofile.seek(0)
             tbinfo = tbinfofile.read()
             _msg = '(%s.%s) :: ERROR due to "%s"\n%s.' % (
                 ObjectTypeName.typeName(self), misc.funcName(), details,
                 tbinfo)
             print >> sys.stderr, _msg
             raise smtplib.SMTPConnectError(_msg)
         self.log = self.logger
     else:
         _msg = '(%s.%s) :: WARNING :: Invalid SMTP Configuration that does not work, recommend checking your choices and attributes because something is wrong. smtpServer=[%s], port=[%s], username=[%s], password=[%s]' % (
             ObjectTypeName.typeName(self), misc.funcName(),
             self.smtp_server, self.smtp_port, self.smtp_username,
             self.smtp_password)
         print >> sys.stderr, _msg
         raise ValueError(_msg)
Пример #10
0
    def __setattr__(self, name, value):

        """ Import the module on demand and set the attribute.
        """
        if (not self.__lazyimport_init):
            self.__dict__[name] = value
            return
        if (self.__lazyimport_loaded):
            self.__lazyimport_locals[self.__lazyimport_name] = value
            self.__dict__[name] = value
            return
        if (_utils.isBeingDebugged) and (_utils.isVerbose):
            print '%s: Module load triggered by attribute %r write access' % (ObjectTypeName.typeName(self),name)
        module = self.__lazyimport_import()
        setattr(module, name, value)
Пример #11
0
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.STAY_ON_TOP
        self.bitmapFile = kwds['bitmapFile']
        del kwds['bitmapFile']
        wx.Frame.__init__(self, *args, **kwds)

        if (ObjectTypeName.typeName(self.bitmapFile) == 'wx._core.Image'):
            self.bitmap = wx.StaticBitmap(self, -1,
                                          wx.BitmapFromImage(self.bitmapFile))
        elif (os.path.exists(self.bitmapFile)):
            self.bitmap = wx.StaticBitmap(
                self, -1, wx.Bitmap(self.bitmapFile, wx.BITMAP_TYPE_ANY))
        else:
            self.bitmap = None

        self.__set_properties()
        self.__do_layout()
Пример #12
0
 def __call__(self, *args):
     _name = misc.callersName()
     _l = [
         '_'.join(str(c).split()) for c in args
         if ObjectTypeName.typeName(c).find('.') == -1
     ]
     _key = '_'.join(_l)
     if (self.cache[_name] == None):
         self.cache[_name] = {}
     try:
         return self.cache[_name][_key]
     except KeyError:
         self.cache[_name][_key] = value = self.func(*args)
         return value
     except TypeError, e:
         # uncachable -- for instance, passing a list as an argument.
         # Better to not cache than to blow up entirely.
         return self.func(*args)
Пример #13
0
 def end(self, evt):
     if (ObjectTypeName.typeName(self.frame) != 'wx._core._wxPyDeadObject'):
         self.__delay__ -= self.delay
         self.min_delay -= self.delay
         if (self.isVerbose):
             print '(%s) :: self.delay=%s, self.min_delay=%s, self.__delay__=%s' % (
                 ObjectTypeName.objectSignature(self), self.delay,
                 self.min_delay, self.__delay__)
         bool = False
         if (callable(self.__callback__)):
             bool = self.__callback__() and (self.min_delay <= 0)
             if (self.isVerbose):
                 print '(%s) :: bool=%s, self.min_delay=%s' % (
                     ObjectTypeName.objectSignature(self), bool,
                     self.min_delay)
         if (bool) or (self.__delay__ <= 0):
             if (bool):
                 self.timer.Stop()
                 self.frame.Destroy()
Пример #14
0
 def fromDict(self, d):
     try:
         if (d.keys()) and (d.values()):
             for k, v in d.iteritems():
                 try:
                     if (v.keys()) and (v.values()):
                         cc = '%s()' % ObjectTypeName.typeName(self).split(
                             '.')[-1]
                         new_d = eval(cc)
                         new_d.fromDict(v)
                         self[k] = new_d
                 except:
                     if (isinstance(v, list)):
                         for item in v:
                             self[k] = item
                     else:
                         self[k] = v
     except:
         pass
     return self
Пример #15
0
 def column(self,name_or_number):
     '''Retrieve a whole column of data by name or number, the name must be a valid column header or the sero-based number must reference a valid column header.'''
     s = str(name_or_number)
     guess = self.__by_col__[s]
     if (not guess) and (s.isdigit()):
         guess = self.__by_col__[self.header[int(s)]]
     if (guess):
         return guess
     _msg = '(%s.%s) :: Cannot return data for column "%s" because this number does not match the number of columns (%d) from row #1.' % (ObjectTypeName.typeName(self),misc.funcName(),name_or_number,self.num_headers)
     logging.warning(_msg)
     raise ValueError(_msg)
Пример #16
0
 def __init__(self, func):
     self.func = func
     self.cache = lists.HashedLists2()
     self.objType = ObjectTypeName.typeName(self)
Пример #17
0
    def process_message(self, peer, mailfrom, rcpttos, data):
        f_unpack = lambda foo, key: foo[key][0] if (misc.isList(foo[key])
                                                    ) else foo[key]
        try:
            SmtpMailsinkServer._count_messages += 1
            try:
                d = self.parseMessage(data)
            except:
                exc_info = sys.exc_info()
                info_string = '\n'.join(traceback.format_exception(*exc_info))
                logMessage(info_string,
                           ObjectTypeName.typeName(self),
                           misc.funcName(),
                           _logging=standardLogging.LoggingLevels.error)
            if (self.multi_file):
                _toAddr = f_unpack(d, const_to_symbol)
                _path = _utils.safely_mkdir(fpath=self.cwd,
                                            dirname=os.sep.join(
                                                ['mailboxes', _toAddr]))
                _fMbx = self.mailboxFile
                self.mailboxFile = open(
                    '%s.%s' % (os.sep.join([
                        _path, _utils.timeStamp().replace(':', '')
                    ]), 'html' if (self.use_html) else 'txt'), 'w')
            info_string = 'DEBUG: self.mailboxFile is "%s".' % (
                self.mailboxFile)
            logMessage(info_string,
                       ObjectTypeName.typeName(self),
                       misc.funcName(),
                       _logging=standardLogging.LoggingLevels.error)
            if self.mailboxFile is not None:
                #_utils.print_stderrout("Mail From is %s\n" % mailfrom)
                try:
                    io_buffer = _utils.stringIO()
                    if (self.is_debugging):
                        d.prettyPrint(prefix='',
                                      title='Mail Parts',
                                      fOut=io_buffer)
                    else:
                        if (self.use_html):
                            print >> io_buffer, self.renderHTML(
                                f_unpack(d, const_subject_symbol),
                                f_unpack(d, const_body_symbol))
                        else:
                            print >> io_buffer, '%s' % (f_unpack(
                                d, const_subject_symbol))
                            print >> io_buffer, '%s' % ('\n'.join(
                                f_unpack(d, const_body_symbol)))
                    s = io_buffer.getvalue()
                    self.mailboxFile.write(s)
                except:
                    exc_info = sys.exc_info()
                    info_string = '\n'.join(
                        traceback.format_exception(*exc_info))
                    logMessage(info_string,
                               ObjectTypeName.typeName(self),
                               misc.funcName(),
                               _logging=standardLogging.LoggingLevels.error)
                #self.mailboxFile.write( "="*80 )
                #self.mailboxFile.write( "\n\n" )
                self.mailboxFile.flush()
                if (self.multi_file):
                    self.mailboxFile.close()
                    self.mailboxFile = _fMbx
            else:
                print >> sys.stderr, 'ERROR: self.mailboxFile is "%s".' % (
                    self.mailboxFile)

            if (callable(self.callback)):
                try:
                    info_string = 'DEBUG: mailfrom is "%s", rcpttos is "%s".' % (
                        mailfrom, rcpttos)
                    logMessage(info_string,
                               ObjectTypeName.typeName(self),
                               misc.funcName(),
                               _logging=standardLogging.LoggingLevels.error)
                    self.callback(d, mailfrom, rcpttos, data)
                except:
                    exc_info = sys.exc_info()
                    info_string = '\n'.join(
                        traceback.format_exception(*exc_info))
                    logMessage(info_string,
                               ObjectTypeName.typeName(self),
                               misc.funcName(),
                               _logging=standardLogging.LoggingLevels.error)
            else:
                logMessage(
                    'Cannot issue callback because callback is not callable.',
                    ObjectTypeName.typeName(self),
                    misc.funcName(),
                    _logging=standardLogging.LoggingLevels.warning)

            info_string = 'SmtpMailsinkServer._count_messages=%d' % (
                SmtpMailsinkServer._count_messages)
            logMessage(info_string,
                       ObjectTypeName.typeName(self),
                       misc.funcName(),
                       _logging=standardLogging.LoggingLevels.info)
        except:
            exc_info = sys.exc_info()
            info_string = '\n'.join(traceback.format_exception(*exc_info))
            logMessage(info_string,
                       ObjectTypeName.typeName(self),
                       misc.funcName(),
                       _logging=standardLogging.LoggingLevels.error)
Пример #18
0
    def renderHTML(self, subj, body):
        from vyperlogix.html import myOOHTML as oohtml
        h_html = oohtml.Html()

        def renderBody(_body):
            h = oohtml.Html()
            h_html = h.tag(oohtml.oohtml.HTML)
            h_body = h_html.tag(oohtml.oohtml.BODY)
            h_Content = h_body.tag(oohtml.oohtml.DIV,
                                   id="content",
                                   style="background-color: white")
            _body = _body[0] if (misc.isList(_body)) and (len(_body)
                                                          == 1) else _body
            h_Content.text(_body[0])
            if (len(_body) > 1):
                for b in _body[1:]:
                    h_Content.tagOp(oohtml.oohtml.BR)
                    h_Content.text(b)
            return h_Content.toHtml()

        if (not misc.isString(subj)):
            subj = str(subj)
        if (not misc.isList(body)):
            body = [body]
        if (misc.isString(subj)) and (misc.isList(body)):
            h_html.text(oohtml.oohtml.DOCTYPE_40_TRANSITIONAL)

            _title = "Vyper Logix SMTP Email Proxy (%s v.%s)" % (
                ObjectTypeName.typeName(self), __version__)
            html_html = h_html.tag(oohtml.oohtml.HTML)
            head_html = html_html.tag(oohtml.oohtml.HEAD)
            head_html.tagOp(oohtml.oohtml.META,
                            http_equiv=oohtml.oohtml.CONTENT_TYPE,
                            content=oohtml.oohtml.TEXT_HTML_CHARSET_ISO_8859_1)
            head_html.metas((
                oohtml.oohtml.AUTHOR, '%s :: %s' %
                (self.author, self.__author__)
            ), (oohtml.oohtml.KEYWORDS, _title), (
                oohtml.oohtml.DESCRIPTION,
                "The contents of this email are considered to be confidential unless otherwise specified."
            ), (oohtml.oohtml.ROBOTS, oohtml.oohtml.ALL))
            head_html.tagTITLE(
                '&copy;%s, Vyper Logix Corp., All Rights Reserved., %s' %
                (_utils.timeStamp(format=_utils.formatDate_YYYY()), _title))
            body_html = html_html.tag(oohtml.oohtml.BODY)
            idContent = body_html.tag(oohtml.oohtml.DIV,
                                      id="content",
                                      style="background-color: white")

            rows = []
            rows.append(tuple(['%s' % (subj)]))
            rows.append(tuple([renderBody(body)]))
            rows.append(tuple(['<BR/><BR/><BR/><BR/>']))
            rows.append(
                tuple([
                    self.copyright if (misc.isString(self.copyright)) and
                    (len(self.copyright) > 0) else self.__copyright__
                ]))
            idContent.html_table(rows)
            pass
        else:
            logMessage(
                'subj must be of type str and body must be of type list rather than of types "%s" and "%s", respectively.'
                % (type(subj), type(body)),
                ObjectTypeName.typeName(self),
                misc.funcName(),
                _logging=standardLogging.LoggingLevels.warning)
        return h_html.toHtml()
Пример #19
0
    def parse(self):
        fIn = open(self.filename,'r')
        try:
            lines = [l.strip() for l in fIn.readlines()]
        finally:
            fIn.close()

        self.__header__ = [h.strip() for h in lines[0].split(',') if (len(h) > 0)]
        self.__num_headers__ = len(self.header)
        for i in xrange(0,len(self.header)):
            self.__row_by_col__[self.header[i]] = lists.HashedLists()
        _re = re.compile('"[^"\r\n]*"|[^,\r\n]*', re.MULTILINE)
        for l in lines[1:]:
            recs = [match.group().replace('"','') for match in _re.finditer(l)]
            if (len(recs) != len(self.header)):
                i = 0
                n = len(recs)
                while (i < (n-1)):
                    can_remove = (len(recs[i]) > 0) and (len(recs[i+1]) == 0)
                    if (can_remove):
                        del recs[i+1]
                        n = len(recs)
                    i += 1
            len_header = len(self.header)
            len_recs = len(recs)
            _num_missing_cols = len_header - len_recs
            if (_num_missing_cols > 0):
                _msg = '(%s.%s) :: CSV parser warning "%s", number of fields do not match the first line, padding with "MISSING" data.' % (ObjectTypeName.typeName(self),misc.funcName(),l)
                logging.warning(_msg)
                for i in xrange(0,_num_missing_cols):
                    recs.append('MISSING')
                _num_missing_cols = len(self.header) - len(recs)
                self.__problem_rows__.append(recs)
            elif (_num_missing_cols == 0):
                self.__rows__.append(recs)
                for i in xrange(0,len(self.header)):
                    self.__by_col__[self.header[i]] = recs[i]
                    self.__row_by_col__[self.header[i]][recs[i]] = recs
            elif (_num_missing_cols < 0):
                self.__rows__.append(recs)
Пример #20
0
 def mouse_action(self, evt):
     if (callable(self.__callback__)):
         return
     self.timer.Stop()
     if (ObjectTypeName.typeName(self.frame) != 'wx._core._wxPyDeadObject'):
         self.frame.Destroy()
Пример #21
0
 def parse(self,dict2_factory=dict):
     '''dict2_factory is optional and specifies a class to be used when making each record.'''
     self.__header__ = None
     self.fIn = open(self.filename,'r')
     _re = re.compile('"[^"\r\n]*"|[^,\r\n]*', re.MULTILINE)
     for l in self.fIn:
         l = str(l).strip()
         if (self.__header__ is None):
             self.__header__ = [h.strip() for h in l.split(',') if (len(h) > 0)]
             self.__num_headers__ = len(self.header)
             for i in xrange(0,len(self.header)):
                 self.__row_by_col__[self.header[i]] = lists.HashedLists()
         recs = [match.group().replace('"','') for match in _re.finditer(l)]
         if (len(recs) != len(self.header)):
             i = 0
             n = len(recs)
             while (i < (n-1)):
                 can_remove = (len(recs[i]) > 0) and (len(recs[i+1]) == 0)
                 if (can_remove):
                     del recs[i+1]
                     n = len(recs)
                 i += 1
         len_header = len(self.header)
         len_recs = len(recs)
         _num_missing_cols = len_header - len_recs
         if (_num_missing_cols > 0):
             _msg = '(%s.%s) :: CSV parser warning "%s", number of fields do not match the first line, padding with "MISSING" data.' % (ObjectTypeName.typeName(self),misc.funcName(),l)
             logging.warning(_msg)
             for i in xrange(0,_num_missing_cols):
                 recs.append('MISSING')
             _num_missing_cols = len(self.header) - len(recs)
             self.__problem_rows__.append(recs)
         elif (_num_missing_cols == 0):
             for i in xrange(0,len(self.header)):
                 self.__by_col__[self.header[i]] = recs[i]
                 self.__row_by_col__[self.header[i]][recs[i]] = recs
             yield recs if (dict2_factory) else self.__rowAsRecords__(recs,dict2_factory=dict2_factory)
         elif (_num_missing_cols < 0):
             yield recs if (dict2_factory) else self.__rowAsRecords__(recs,dict2_factory=dict2_factory)
     self.fIn.close()