def store_in_bucket_recursive(bucket={},fp=None):

        def packit(fp):
            toks = [t for t in fp.split('/') if t]
            ret = fp
            for tok in reversed(toks):
                ret = {tok: ret}
            return ret
        
        def merge(d1, d2):
            for k1,v1 in d1.iteritems():
                if not k1 in d2:
                    d2[k1] = v1
                elif isinstance(v1, dict):
                    merge(v1, d2[k1])
            return d2

        if (not fp):
            paths = ['1/2/3','1/2/4','1/2/5']
        else:
            paths = [fp] if (not misc.isList(fp)) else fp
        dicts = [packit(p) for p in paths]
        merged = bucket if (misc.isDict(bucket)) else {}
        for d in dicts:
            merged = merge(merged,d)
        return merged
Beispiel #2
0
 def set_date(self, dt):
     if (misc.isList(dt)):
         dt = '/'.join([str(n) for n in dt])
     self.__date = [
         int(n) if misc.isString(n) else n for n in self.parseDate(dt)
     ]
     self.__mm, self.__dd, self.__yyyy = self.__date
     self.__julianDate = julian.Julian(self.__mm, self.__dd, self.__yyyy)
Beispiel #3
0
 def __call__(self, *args, **kwargs):
     n = self.n[0] if misc.isList(self.n) else self.n
     s = 'self.__object__.%s(*args,**kwargs)' % (n)
     try:
         results = eval(s)
     except Exception as details:
         results = None
         print >> sys.stderr, _utils.formattedException(details=details)
     return results
Beispiel #4
0
 def asDict(self, cls=lists.HashedLists2):
     '''cls can also be dict to allow for normal native dict objects to be returned for safe pickling using the standard Python pickle methods.'''
     d = cls()
     for k, v in self.__dict__.iteritems():
         d[real_k(k)] = [asPythonDict(item) for item in v
                         ] if (misc.isList(v)) else asPythonDict(v) if (
                             lists.isDict(v)) else v.asPythonDict() if (
                                 isSmartObject(v)) else v
     return d
Beispiel #5
0
    def getPortalContacts(self,for_accounts=[],callback=None,limit=None):
	soql = "Select Id, AccountId, ContactStatus__c from Contact where (ContactStatus__c = 'Active')"
	if (misc.isList(for_accounts)):
	    soql += " and (AccountId in (%s))" % (','.join(["'%s'" % (id) for id in for_accounts if (misc.isString(id))]))
	else:
	    soql += " and (AccountId != NULL)"
	if (limit is not None):
	    soql += ' LIMIT %s' % (limit)
	return self.sf_query(soql,callback=callback)
Beispiel #6
0
def _commitTarget(cmds):
    from vyperlogix.process import Popen

    cmds = cmds if (misc.isList(cmds)) else [cmds]
    reportTheList(cmds,'Commands')
    buf = StringIO()
    shell = Popen.Shell(cmds,isExit=True,isWait=True,isVerbose=True,fOut=buf)
    print buf.getvalue()
    print '-'*40
    print
Beispiel #7
0
 def __call__(self, *args, **kwargs):
     items = []
     items.append(args)
     items.append(kwargs)
     n = self.n
     if (misc.isList(n)):
         self.__store_magic__({n[0]: {n[-1]: tuple(items)}})
     else:
         self.__store_magic__({n: tuple(items)})
     return self.__magic__
Beispiel #8
0
 def __getattr__(self, name):
     values = []
     keys = [
         k for k in self.__dict__.keys()
         if (str(k).lower() == str(name).lower())
     ]
     for key in keys:
         values.append(super(SmartFuzzyObject, self).__getattr__(key))
     return values if (len(values) > 1) else values[0] if (
         misc.isList(values)) and (len(values) > 0) else values
Beispiel #9
0
 def __setitem__(self, key, value):
     key = key if (misc.isString(key)) else str(key)
     if (self.has_key(key)):
         bucket = super(PickledHash2, self).__getitem__(key)
         if (misc.isList(bucket)):
             bucket.append(value)
             super(PickledHash2, self).__setitem__(key, bucket)
         else:
             super(PickledHash2, self).__setitem__(key, [value])
     else:
         super(PickledHash2, self).__setitem__(key, value)
Beispiel #10
0
def get_from_session(request, name, default=None):
    from vyperlogix.hash import lists
    from vyperlogix.classes.SmartObject import PyroSmartObject

    try:
        obj = request.session.get(name, default)
        return [
            o if (not lists.isDict(o)) else PyroSmartObject(o) for o in obj
        ] if (misc.isList(obj)) else obj if (
            not lists.isDict(obj)) else PyroSmartObject(obj)
    except:
        pass
    return ''
Beispiel #11
0
def put_data(_fname, key, value, fOut=None, isUnique=True):
    dbx = PickledFastCompressedHash2(_fname)
    try:
        value = value if (not misc.isList(value)) else value[0]
        if (isUnique) and (dbx.has_key(key)):
            del dbx[key]
        dbx[key] = value
    except Exception as details:
        from vyperlogix.misc import _utils
        fOut = sys.stderr if (fOut is None) else fOut
        print >> fOut, _utils.formattedException(details)
    finally:
        dbx.close()
Beispiel #12
0
 def queryMostlyANDitems(self, *args):
     recs = set()
     for arg in args:
         items = []
         if (self.has_key(arg)):
             items = self[arg]
             if (not misc.isList(items)):
                 items = [items]
         items = set(items)
         if len(recs) == 0:
             recs = items
         elif len(recs & items) > 0:
             recs &= items
     return list(recs)
Beispiel #13
0
def todays_events(server,logtype,ids=[4648]):
    import datetime
    from vyperlogix import misc
    from vyperlogix.misc import _utils
    from vyperlogix.hash.lists import HashedLists
    from vyperlogix.classes.SmartObject import SmartObject
    
    import win32evtlog
    
    #logon_event_ids = [id for id in [int(e.id) for e in events_by_tokens.get('logon',[])] if (id > 999)]
    logon_event_ids = ids if (misc.isList(ids)) else [4648]
    
    hand = win32evtlog.OpenEventLog(server,logtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    
    now = _utils.today_localtime()
    
    seconds_in_day = 24*60*60
    
    __todays_events__ = []
    
    __running__ = True
    while (__running__):
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                if (event.EventID in logon_event_ids):
                    #print 'Event Category:', event.EventCategory
                    #print 'Time Generated:', event.TimeGenerated
                    dt = _utils.getFromDateTimeStr(event.TimeGenerated.Format(),format='%m/%d/%y %H:%M:%S')
                    delta = max(now,dt) - min(now,dt)
                    #print 'delta.total_seconds()=%s' % (delta.total_seconds())
                    if (delta.total_seconds() < seconds_in_day):
                        __todays_events__.append(event)
                    else:
                        __running__ = False
                        break
                    #print 'Source Name:', event.SourceName
                    #print 'Event ID:', event.EventID
                    #print 'Event Type:', event.EventType
                    #data = event.StringInserts
                    #if data:
                        #print 'Event Data:'
                        #for msg in data:
                            #print msg
                    #print '='*40
        else:
            break
    return __todays_events__
Beispiel #14
0
 def __http_gets__(self, url, parms=[]):
     data = None
     try:
         q = ''
         if (misc.isList(parms)) and (len(parms) > 0):
             q = '?' + '&'.join(
                 ['%s=%s' % (p[0], urllib2.quote(p[-1]))
                  for p in parms]) if (len(parms) > 0) else ''
         response = urllib2.urlopen(url + q)
         data = response.read()
     except Exception as ex:
         self.__last_exception__ = _utils.formattedException(details=ex)
         data = None
     return data
Beispiel #15
0
def form_as_html(form, request=None, callback=None, context={}):
    from vyperlogix.django.forms import templates

    form_html = _form_for_model(form,
                                request=request,
                                callback=callback,
                                context=context)
    form_template = templates.template_for_form(form_html)
    if (request is not None):
        for name, value in request.POST.iteritems():
            context["VALUE_%s" % (name.upper())] = value[0] if (
                misc.isList(value)) else value
    form_content = form_template.render(Context(context))
    return form_content
Beispiel #16
0
 def write_as_csv(self,fname,list_of_records=[],ordering=[]):
     """
     Writes a list of records (dict objects) to a .CSV filename.
     """
     info_string = ''
     info_strings = []
     if (misc.isList(list_of_records)):
         if (len(list_of_records) > 0):
             if (all([lists.isDict(r) for r in list_of_records])):
                 header = list_of_records[0].keys()
                 if (misc.isList(ordering)) and (len(ordering) > 0):
                     header = ordering
                 s_header = ','.join(header)
                 fOut = open(fname,'w')
                 try:
                     print >>fOut, s_header
                     for rec in list_of_records:
                         l_values = []
                         for h in header:
                             l_values.append(str(rec[h]) if (str(rec[h]).find(',') == -1) else '"%s"' % (rec[h]))
                         print >>fOut, ','.join(l_values)
                 except Exception as details:
                     info_string = _utils.formattedException(details=details)
                     info_strings.append(info_string)
                 finally:
                     fOut.flush()
                     fOut.close()
             else:
                 info_string = '%s :: Expected list_of_records to contains dictionary objects however some do not.' % (ObjectTypeName.objectSignature(self))
                 info_strings.append(info_string)
         else:
             info_string = '%s :: Expected list_of_records to contains dictionary objects however list is empty.' % (ObjectTypeName.objectSignature(self))
             info_strings.append(info_string)
     else:
         info_string = '%s :: Expected list_of_records to be of type list rather than type "%s".' % (ObjectTypeName.objectSignature(self),type(list_of_records))
         info_strings.append(info_string)
     return '\n'.join(info_strings)
Beispiel #17
0
def get_data(_fname, key, fOut=None, isUnique=True):
    dbx = PickledFastCompressedHash2(_fname)
    value = None
    try:
        value = dbx[key]
        if (isUnique):
            value = value if (not misc.isList(value)) else None if (
                len(value) == 0) else value[0]
    except Exception as details:
        from vyperlogix.misc import _utils
        fOut = sys.stderr if (fOut is None) else fOut
        print >> fOut, _utils.formattedException(details)
    finally:
        dbx.close()
    return value
Beispiel #18
0
 def __call__(self,*args,**kwargs):
     results = None
     n = self.n[0] if (misc.isList(self.n) and (len(self.n) > 0)) else self.n
     if (len(self.__stack__) > 0):
         n = self.__stack__.pop()
         #obj = SmartWrapper.__cache__.get(self.__id__)
     obj = SmartWrapper.__cache__.get(self.__id__)
     if (obj):
         try:
             f = getattr(obj, n)
             results = f(*args,**kwargs)
         except Exception as details:
             results = None
             sys.stderr.write(_utils.formattedException(details=details)+'\n')
     return results
Beispiel #19
0
 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()
Beispiel #20
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)))
    def acceptContacts(self,asset,contacts):
	clist = self.__competitors_list
	if (misc.isList(contacts)):
	    if (len(contacts) > 0):
		contacts = [c for c in contacts if (c['Email'] is not None) and (c['Email'].split('@')[-1] not in clist)]
		for c in contacts:
		    c['Asset_Name'] = asset['Name']
		    c['Asset_Id'] = asset['Id']
		self.__contacts__ += contacts
	else:
	    info_string = '%s accepts a list of contacts but not when it is of type "%s".' % (ObjectTypeName.objectSignature(self),type(contacts))
	    print >>sys.stderr, info_string
	    try:
		wx_PopUp_Dialog(parent=self.__child_frame,msg=info_string,title='WARNING',styles=wx.ICON_WARNING | wx.CANCEL)
	    except:
		pass
Beispiel #22
0
def patterns_insert(prefix, pattern_list, index, tuples):
    from django.core.urlresolvers import RegexURLPattern, RegexURLResolver

    pattern_list = pattern_list if (
        misc.isList(pattern_list)) else [pattern_list]
    for t in tuples:
        regex, view_or_include = t[:2]
        default_kwargs = t[2:]
        if type(view_or_include) == list:
            pattern_list.append(
                RegexURLResolver(regex, view_or_include[0], *default_kwargs))
        else:
            pattern_list.append(
                RegexURLPattern(
                    regex, prefix and (prefix + '.' + view_or_include)
                    or view_or_include, *default_kwargs))
    return pattern_list
Beispiel #23
0
def asJSONSerializable(__dict__):
    def asJSON(vv):
        return misc._unpack_([asJSONSerializable(_vv)
                              for _vv in vv]) if (misc.isList(vv)) else vv

    try:
        iterable = __dict__
        is_or_has_dict = False
        if (isDict(__dict__)):
            is_or_has_dict = True
            iterable = __dict__
        else:
            try:
                __dict__.__dict__
                is_or_has_dict = True
                iterable = __dict__.__dict__
            except:
                pass
        if (is_or_has_dict):
            dObj = {}
            for k, v in iterable.iteritems():
                if (not callable(v)):
                    try:
                        if (isDict(v)) or (isDict(v.__dict__)):
                            dObj[k] = asJSONSerializable(v)
                        else:
                            dObj[k] = asJSON(v)
                    except AttributeError:
                        dObj[k] = asJSON(v)
        elif (misc.isList(iterable)):
            dObj = []
            for v in iterable:
                if (not callable(v)):
                    try:
                        if (isDict(v)) or (isDict(v.__dict__)):
                            dObj.append(asJSONSerializable(v))
                        else:
                            dObj.append(asJSON(v))
                    except AttributeError:
                        dObj.append(asJSON(v))
        else:
            return iterable
    except:
        pass
    return dObj
Beispiel #24
0
 def __init__(self, fname=None, dateSpec=None):
     self.__items = []
     self.fileName = fname if (misc.isString(fname)) and (os.path.exists(
         fname)) else 'Z:/#zDisk/#IRS/Microsoft Money (1996-2007).qif'
     self.dateSpec = dateSpec
     if (self.dateSpec):
         if (misc.isList(self.dateSpec)):
             if (len(self.dateSpec) >= 1):
                 if (misc.isString(self.dateSpec[0])):
                     self.dateSpec[0] = self.dateSpecToFloat(
                         self.dateSpec[0])
             if (len(self.dateSpec) > 1):
                 if (misc.isString(self.dateSpec[-1])):
                     self.dateSpec[-1] = self.dateSpecToFloat(
                         self.dateSpec[-1])
         elif (misc.isString(self.dateSpec)):
             self.dateSpec = [self.dateSpecToFloat(self.dateSpec)]
         else:
             self.dateSpec = [self.dateSpec]
Beispiel #25
0
def rss_content(url, source_domain='', target_domain=''):
    import urllib

    from vyperlogix.rss import reader
    from vyperlogix.html import myOOHTML as oohtml

    from vyperlogix import misc

    try:
        rss = reader.read_feed_links(url)
    except Exception as e:
        rss = [['CANNOT ACCESS NEWS FEED :: %s' % (str(e)), url, '']]

    toks = list(urllib.splitquery(url))
    u = 'http://' + toks[0].split('http://')[-1].split('/')[0]
    if (len(source_domain) > 0) and (len(target_domain) > 0):
        u = u.replace(source_domain, target_domain)
    link = oohtml.renderAnchor(u, u)
    items = [['<h3 align="center">%s</h3>' % (link)]]

    h = oohtml.Html()
    if (misc.isList(rss)):
        try:
            ul = h.tag(oohtml.oohtml.UL)
            for item in rss:
                if (len(source_domain) > 0) and (len(target_domain) > 0):
                    item[1] = item[1].replace(source_domain, target_domain)
                rss_link = oohtml.renderAnchor('%s' % (item[1]), item[0])
                words = item[2].split()
                item[2] = ' '.join(words[0:0])
                ul._tagLI('%s<br/><small>%s</small>' %
                          (rss_link, '<br/>'.join(item[2:])))
        except:
            h.tagTEXTAREA('ERROR: %s' % (rss), rows=10, cols=80)
    else:
        h.tagTEXTAREA('ERROR: %s' % (rss), rows=10, cols=80)
    items += [[h.toHtml()]]

    h = oohtml.Html()
    h.html_simple_table(items)
    content = h.toHtml()
    return content
Beispiel #26
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
Beispiel #27
0
 def x(*args, **kwargs):
     key = sha1(
         str(f.__module__) + str(f.__name__) + str(args) +
         str(kwargs)).hexdigest()
     result = _djcache.get(key)
     if (result is None):
         result = f(*args, **kwargs)
         _result = [
             item if (not SmartObject.isSmartObject(item)) else
             item.asPythonDict() for item in result
         ]
         _result = pickleItem(_result)
         _djcache.set(key, _result, seconds)
     else:
         result = unPickleItem(result)
         if (misc.isList(result)):
             if (all([misc.isString(item) for item in result])):
                 result = ''.join(result)
         else:
             pass
     return result
Beispiel #28
0
    def __init__(self, line, epoch=DEFAULT_EPOCH, epoch_utc_offset=0):
        """
        Instantiates a CronExpression object with an optionally defined epoch.
        If the epoch is defined, the UTC offset can be specified one of two
        ways: as the sixth element in 'epoch' or supplied in epoch_utc_offset.
        The epoch should be defined down to the minute sorted by
        descending significance.
        """
        for key, value in SUBSTITUTIONS.items():
            if line.startswith(key):
                line = line.replace(key, value)
                break

        fields = line.split(None, 5)
        if len(fields) == 5:
            fields.append('')

        minutes, hours, dom, months, dow, self.comment = fields if (
            (misc.isTuple(fields) or misc.isList(fields)) and
            (len(fields) == 6)) else ('', '', '', '', '', '')

        dow = dow.replace('7', '0').replace('?', '*')
        dom = dom.replace('?', '*')

        for monthstr, monthnum in MONTH_NAMES:
            months = months.lower().replace(monthstr, str(monthnum))

        for dowstr, downum in DAY_NAMES:
            dow = dow.lower().replace(dowstr, str(downum))

        self.string_tab = [minutes, hours, dom.upper(), months, dow.upper()]
        self.compute_numtab()
        if len(epoch) == 5:
            y, mo, d, h, m = epoch
            self.epoch = (y, mo, d, h, m, epoch_utc_offset)
        else:
            self.epoch = epoch
Beispiel #29
0
    def __init__(self, parent, title, onProcess_callback=None, onClose_callback=None, callback_is_running_securely_for_developers=None):
        self.__onProcess_callback = onProcess_callback
        self.__onClose_callback = onClose_callback
	
        from vyperlogix.wx.pyax import SalesForceLoginModel
        self.__sf_login_model__ = SalesForceLoginModel.SalesForceLoginModel(callback_developers_check=callback_is_running_securely_for_developers)
        isStaging = self.__sf_login_model__.isStaging
	
        wx.Dialog.__init__(self, parent, -1, title, wx.DefaultPosition, (300, 160), style=wx.SYSTEM_MENU | wx.CAPTION | wx.STAY_ON_TOP) # | wx.CLOSE_BOX | wx.RESIZE_BORDER | 0 | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX
        self.panel = wx.Panel(self, -1)

        self.labelUsername = wx.StaticText(self.panel, -1, 'UserName:'******'Microsoft Sans Serif'))
        self.labelUsername.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))

        self.textUsername = wx.TextCtrl(self.panel, -1, 'username', (96,8), size=(185, 20))
        self.textUsername.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.textUsername.SetFont(wx.Font(8.25, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, 'Microsoft Sans Serif'))
        self.textUsername.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))

        self.labelPassword = wx.StaticText(self.panel, -1, 'Password:'******'Microsoft Sans Serif'))
        self.labelPassword.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))

        self.textPassword = wx.TextCtrl(self.panel, -1, 'password', (96,32), size=(185, 20), style=wx.TE_PASSWORD | wx.TE_PROCESS_ENTER)
        self.textPassword.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.textPassword.SetFont(wx.Font(8.25, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, 'Microsoft Sans Serif'))
        self.textPassword.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))

	servers = []
	for k,v in self.__sf_login_model__.sfServers.iteritems():
	    servers += v if (misc.isList(v)) else [v]
        self.cbServerEndPoints = wx.ComboBox(self.panel, -1, 'combobox for Server End-Points', (164,136), (180, 21), servers, style=wx.CB_READONLY | wx.CB_SORT)
        self.cbServerEndPoints.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.cbServerEndPoints.SetFont(wx.Font(8.25, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, 'Microsoft Sans Serif'))
        self.cbServerEndPoints.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
	self.cbServerEndPoints.SetSelection(0)

        self.textEndPoint = wx.TextCtrl(self.panel, -1, 'endpoint', (96,8), size=(300, 20))
        self.textEndPoint.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.textEndPoint.SetFont(wx.Font(8.25, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, 'Microsoft Sans Serif'))
        self.textEndPoint.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
	self.textEndPoint.SetValue(self.sf_login_model.get_endpoint(self.cbServerEndPoints.GetValue()))

        self.btnLogin = wx.Button(self.panel, -1, 'Login', (24,96), (75, 23))
        self.btnLogin.SetFont(wx.Font(8.25, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, 'Microsoft Sans Serif'))
        self.btnLogin.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))

        self.btnCancel = wx.Button(self.panel, -1, 'Cancel', (120,96), (75, 23))
        self.btnCancel.SetFont(wx.Font(8.25, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, 'Microsoft Sans Serif'))
        self.btnCancel.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))

        self.boxRadioButtons = wx.StaticBox(self.panel, -1, "SalesForce End-Points" )
        self.boxRadioButtons.SetFont(wx.Font(8.25, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, 'Microsoft Sans Serif'))
        self.boxRadioButtons.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))

        import salesforce_icon
        self.SetIcon(wx.IconFromBitmap(salesforce_icon.getsalesforce_iconBitmap()))

        vbox = wx.BoxSizer(wx.VERTICAL)

        hboxes = []

        box1 = wx.StaticBoxSizer( self.boxRadioButtons, wx.VERTICAL )
        sizer = rcs.RowColSizer()

	sizer.Add(self.cbServerEndPoints, row=0, col=1)
	sizer.Add(self.textEndPoint, row=1, col=1)

        box1.Add(sizer, 0, wx.ALIGN_LEFT | wx.ALL, 5 )

        hboxes.append(wx.BoxSizer(wx.HORIZONTAL))
        hboxes[-1].Add(self.labelUsername, 0, wx.RIGHT, 8)
        hboxes[-1].Add((5, -1))
        hboxes[-1].Add(self.textUsername, 1)
        vbox.Add(hboxes[-1], 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)

        vbox.Add((-1, 1))

        hboxes.append(wx.BoxSizer(wx.HORIZONTAL))
        hboxes[-1].Add(self.labelPassword, 0, wx.RIGHT, 8)
        hboxes[-1].Add((5, -1))
        hboxes[-1].Add(self.textPassword, 1)
        vbox.Add(hboxes[-1], 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)

        vbox.Add((-1, 1))

        vbox.Add(box1, 0, wx.ALIGN_LEFT | wx.ALL, 10)
        vbox.Add((-1, 1))

        hboxes.append(wx.BoxSizer(wx.HORIZONTAL))
        hboxes[-1].Add(self.btnLogin, 0, wx.RIGHT, 8)
        hboxes[-1].Add((5, -1))
        hboxes[-1].Add(self.btnCancel, 1)
        vbox.Add(hboxes[-1], 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)

        vbox.Add((-1, 1))

        self.panel.SetSizer(vbox)

        x = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
        y = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

        self.SetSizeHints(300,160,x,y)
        vbox.Fit(self)

        self.Bind(wx.EVT_BUTTON, self.onProcess, self.btnLogin)
        self.Bind(wx.EVT_BUTTON, self.OnClose, self.btnCancel)
	
        self.Bind(wx.EVT_COMBOBOX, self.OnSelectedServerEndPoints, self.cbServerEndPoints)

        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.Bind(wx.EVT_TEXT_ENTER, self.onProcess, self.textPassword)
Beispiel #30
0
    def __init__(self,commands,shell=None,env=None,isExit=False,isWait=False,isVerbose=False,fOut=sys.stderr,onExit=None):
        '''
        isVerbose=True and fOut=something work together otherwise there will be no putput from the commands that were issued.
        fOut=something callable to get callbacks rather than waiting for the end result.
        '''
        self.isVerbose = isVerbose
        self.fOut = fOut
        self.__onExit__ = onExit
	self.__delayed__ = []
	self.__has_issued_callback__ = False
        if (callable(fOut)):
            self.isVerbose = True
        if (not misc.isList(commands)):
            commands = [commands]
        if sys.platform == 'win32':
            shell, commands, self.tail = ('cmd' if (shell is None) else shell, commands, '\r\n')
        else:
            shell, commands, self.tail = ('sh' if (shell is None) else shell, commands, '\n')

        e = os.environ if (env == None) else env
        self.proc = Popen(shell, env=e, stdin=PIPE, stdout=PIPE)
        if (self.isVerbose):
            if (callable(fOut)):
                try:
                    fOut(recv_some(self.proc))
                except Exception as details:
                    info_string = _utils.formattedException(details=details)
                    print >> sys.stdout, info_string
            else:
                print >>self.fOut, recv_some(self.proc),
        for cmd in commands:
            send_all(self.proc, str(cmd) + self.tail)
            if (self.isVerbose):
                __lines__ = []
                data = recv_some(self.proc)
		__toks__ = str(data).split(os.linesep)
		# there is still a timing issue - wait 30 secs or count nothing returned something like 10 times...
		_begin_ = time.time()
		_num_ = 0
		_max_ = 30
                while ((time.time() - _begin_) < _max_) and (_num_ < _max_):
		    if (len(__toks__) > 1):
			misc.append(__lines__,__toks__)
		    else:
			_num_ += 1
		    time.sleep(1)
                    data = recv_some(self.proc)
		    __toks__ = str(data).split(os.linesep)
		self.__has_issued_callback__ = True
		if (callable(fOut)):
		    try:
			fOut(os.linesep.join(__lines__))
		    except Exception as details:
			info_string = _utils.formattedException(details=details)
			print >> _target_[0:2], info_string
		else:
		    print >>self.fOut, recv_some(self.proc),
	while (len(self.__delayed__) > 0):
	    if (callable(self.__delayed__[-1])):
		callee = self.__delayed__.pop()
		try:
		    callee()
		except Exception as details:
		    info_string = _utils.formattedException(details=details)
		    print >> _target_[0:2], info_string
        if (isExit):
	    if (not self.__has_issued_callback__):
		self.__delayed__.append(self.doExit)
	    else:
		self.doExit()
        if (isWait):
            self.doWait()
Beispiel #31
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)
Beispiel #32
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()