Beispiel #1
0
    def __init__(self, __version__, __func__):
        '''__version__ is the version for the Pyro Server and NS Authentication to ensure the client can connect to the server.'''
        if (_isRunningLocal):
            _beginTime = time.time()

        Pyro_config.PYRO_COMPRESSION = 1
        Pyro_config.PYRO_CHECKSUM = 1
        Pyro_config.PYRO_SOCK_KEEPALIVE = 1
        Pyro_config.PYRO_MULTITHREADED = 1

        Pyro.core.initClient()
        ident = __func__(__version__)

        locator = Pyro.naming.NameServerLocator(identification=ident)
        print '%s :: Searching Naming Service...' % (
            ObjectTypeName.objectSignature(self))
        ns = locator.getNS()

        print '%s :: Naming Service found at %s port %s' % (
            ObjectTypeName.objectSignature(self), ns.URI.address, ns.URI.port)

        print '%s :: Binding to Remote Object.' % (
            ObjectTypeName.objectSignature(self))
        try:
            URI = ns.resolve(':SalesForceProxy.version_%s' %
                             (__version__.replace('.', '_')))
            print '%s :: URI: %s' % (ObjectTypeName.objectSignature(self), URI)
        except Pyro.core.PyroError, x:
            print '%s :: Couldn\'t bind object, nameserver says: %s' % (
                ObjectTypeName.objectSignature(self), x)
            raise SystemExit
Beispiel #2
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
Beispiel #3
0
    def __init__(self,sfQuery,account,role=roles.MoltenPrivileges.Member,tree=AccountTreeNode(-1,"root",None)):
        '''
	account is the name of the account of the Id of the account.
	To-Do: Feed this object a COntact Id and let it figure-out the account for the contact.
	'''
        expected_class_name = ObjectTypeName._typeName(AccountTreeNode).split('.')[-1]
        got_class_name = ObjectTypeName.typeClassName(tree).split('.')[-1]
        self.__tree__ = tree if (expected_class_name == got_class_name) else None
        self.__role__ = role if (roles.isValidMoltenUserRole(role)) else None
        self.__sfQuery__ = sfQuery
        self.__accountId__ = None
        self.__account__ = None
        if (self.__tree__ is None):
            raise ValueError('Invalid value for tree attribute.')
        if (self.__role__ is None):
            raise ValueError('Invalid value for role attribute.')
        try:
            n = tree.findForwards(Id=account)
            if (n is not None):
                self.__accountId__ = n.Id
            else:
                n = tree.findForwards(Name=account)
                if (n is not None):
                    self.__accountId__ = n.Id
            if (self.__account__ is None) and (self.__accountId__ is not None):
                sf_accounts = SalesForceAccounts(self.sfQuery)
                accounts = sf_accounts.getAccountById(self.accountId)
                if (sf_accounts.contains_sf_objects(accounts)):
                    self.__account__ = accounts[0]
        except Exception as details:
            info_string = _utils.formattedException(details=details)
            print >>sys.stderr, info_string
        if (self.__account__ is None):
            raise ValueError('Invalid value for account attribute, account must be the Id or the Name of the account.')
Beispiel #4
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)))
Beispiel #5
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
    def _doAfterExtractionProcessCompleted(self):
        alpha_num_only = lambda s: ' '.join(''.join([
            ch if (ch.isalnum()) else ' ' for ch in s
            if (ch.isalnum()) or (ch in [' ', '_', '-'])
        ]).split('  '))

        self.number = 2
        self.count = 1
        self.deduped_Contacts = self.dedupeContacts(self.__contacts__)
        self.appendText('%s :: (%d/%d) contacts.' %
                        (ObjectTypeName.objectSignature(self),
                         len(self.deduped_Contacts), len(self.__contacts__)))
        if (not os.path.exists(self._csv_model.filename)):
            self._csv_model.filename = os.sep.join(
                [self._log_path, 'data_raw.csv'])
        self.appendText(
            '%s :: BEGIN: "%s".' %
            (ObjectTypeName.objectSignature(self), self._csv_model.filename))
        info_string = CSV.write_as_csv(self._csv_model.filename,
                                       self.__contacts__)
        if (len(info_string) > 0):
            self.appendText('%s :: %s-->%s.' %
                            (ObjectTypeName.objectSignature(self),
                             self._csv_model.filename, info_string))
        self.count = 2
        fname = os.sep.join([self._log_path, 'data_cleaned.csv'])
        info_string = CSV.write_as_csv(fname, self.deduped_Contacts)

        if (len(info_string) > 0):
            self.appendText(
                '%s :: %s-->%s.' %
                (ObjectTypeName.objectSignature(self), fname, info_string))
        self.appendText(
            '%s :: END!   "%s".' %
            (ObjectTypeName.objectSignature(self), self._csv_model.filename))
Beispiel #7
0
 def _rowByColumn(self,key,name_or_number):
     iCol = self.column_number_for_name(name_or_number)
     nCol = self.header[iCol]
     for r in self.rows:
         if (r[iCol] == key):
             rr = self.__row_by_col__[nCol][key]
             assert len(r) == len(rr), '%s Problem with #1.' % (ObjectTypeName.objectSignature(self))
             for i in xrange(0,len(rr)):
                 assert r[i] == rr[i], '%s Problem with #2.' % (ObjectTypeName.objectSignature(self))
             return r
     return None
 def default(self, o):
     obj = {'__class__':ObjectTypeName.typeClassName(o)}
     try:
         for k,v in o.__dict__.iteritems():
             obj[k] = v
     except AttributeError:
         if (ObjectTypeName.typeClassName(o) == 'file'):
             obj['name'] = o.name
             obj['mode'] = o.mode
         else:
             pass
         pass
     return obj
 def func(*args, **kwargs):
     kw = kwargs.items()
     kw.sort()
     key = (args, tuple(kw))
     try:
         v = _cache[key]
         if (self.isDebugging):
             print '\n%s :: cache :: "%s"' % (ObjectTypeName.objectSignature(self),key)
         if (time.time() - v[1]) > self.timeout:
             raise KeyError
     except KeyError:
         if (self.isDebugging):
             print '\n%s :: new (%d) :: "%s"' % (ObjectTypeName.objectSignature(self),len(_cache),key)
         v = _cache[key] = f(*args,**kwargs),time.time()
     return v[0]
Beispiel #10
0
def fetch_downloads_vyperlogix_com_files(regex=__re__):
    from vyperlogix.misc import ObjectTypeName

    __host__ = 'ftp.ord1-1.websitesettings.com'
    __port__ = 22

    __username__ = 'raychorn'

    from vyperlogix.crypto import Encryptors
    __password__ = Encryptors._decode('D0E5E5EBC0E2B0B0')

    __remote__ = '/downloads.vyperlogix.com/web/content'

    from vyperlogix.sockets.scp.RemoteFileSystem import RemoteScp
    scp = RemoteScp(__host__, __port__, __username__, __password__, __remote__)

    if (ObjectTypeName.typeClassName(regex).find('_sre.SRE_Pattern') > -1):
        files = [(f[0], f[-1].groupdict())
                 for f in [(f, regex.match(f))
                           for f in scp.fetch_directory_from_remote_host()]
                 if (f[-1])]
    else:
        files = [f for f in scp.fetch_directory_from_remote_host()]

    return files
Beispiel #11
0
def render_select_content(aList,
                          tag=None,
                          id=None,
                          name=None,
                          text_id=None,
                          value_id=None,
                          defaultChoose=False,
                          onChange=None,
                          selected=None):
    from vyperlogix.misc import ObjectTypeName
    from vyperlogix.classes.SmartObject import SmartObject
    h = Html() if (tag is None) else tag
    if (ObjectTypeName.typeClassName(aList).find('QuerySet') > -1):
        aList = [
            SmartObject(aList[i].__dict__) for i in xrange(0, aList.count())
        ]
    if (isinstance(aList, list)):
        options = []
        if (defaultChoose):
            options.append(('', "Choose..."))
        try:
            options += [(item[value_id], item[text_id]) for item in aList]
        except:
            pass  # don't cry about this just skip over it...
        options = tuple(options)
        h.tagSELECT(options, (selected if (selected) else ''),
                    id=id,
                    name=name,
                    onchange=onChange)
    return h.toHtml()
Beispiel #12
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
Beispiel #13
0
def instance_as_SmartObject(item):
    '''This function fails from time to time so fix it !'''
    from vyperlogix.classes.SmartObject import PyroSmartObject as SmartObject
    d = lists.HashedLists2(
        dict([(k, v) for k, v in item.__dict__.iteritems()
              if (not ObjectTypeName.type_is_class(v))]))
    return SmartObject(d)
def __terminate__():
    from vyperlogix.misc import _utils
    
    from vyperlogix.win.WinProcesses import Win32Processes
    
    from vyperlogix import misc
    from vyperlogix.misc import ObjectTypeName

    __programName__ = (sys.argv[0].split(os.sep)[-1].split('.'))[0]
    try:
	p = Win32Processes()
	pid = p.getProcessIdByName(__programName__)
	if (misc.isList(pid)) and (len(pid) > 0):
	    pid = pid[0]
	elif (len(pid) == 0):
	    pid = os.getpid()
	if (misc.isInteger(pid)):
	    print 'DEBUG:  pid="%s"' % (pid)
	    print 'BEGIN:'
	    _utils.terminate()
	    print 'END !!!'
	else:
	    print 'DEBUG:  pid is not an Int because it is "%s" !!!' % (ObjectTypeName.typeClassName(pid))
    except Exception as ex:
	info_string = _utils.formattedException(details=ex)
	print info_string
Beispiel #15
0
 def __init__(self, *args, **kwds):
     self.isVerbose = False
     if (kwds.has_key('isVerbose')):
         self.isVerbose = kwds['isVerbose']
         del kwds['isVerbose']
     self.delay = -1
     if (kwds.has_key('delay')):
         delay = kwds['delay']
         try:
             self.delay, self.min_delay, self.__delay__ = delay
         except:
             self.delay, self.min_delay, self.__delay__ = (1000, 5000,
                                                           10000)
         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__)
         del kwds['delay']
     self.__callback__ = None
     if (kwds.has_key('callback')):
         self.__callback__ = kwds['callback']
         del kwds['callback']
     self.bitmapFile = ''
     if (kwds.has_key('bitmapFile')):
         self.bitmapFile = kwds['bitmapFile']
         del kwds['bitmapFile']
     wx.App.__init__(self, *args, **kwds)
 def func(*args, **kwargs):
     kw = kwargs.items()
     kw.sort()
     key = (tuple([arg for arg in list(args) if (misc.isString(arg))]), tuple(kw))
     try:
         v = _cache[key]
         et = time.time() - v[1]
         if (self.isDebugging):
             print '\n%s :: cache :: "%s"' % (ObjectTypeName.objectSignature(self),key)
         if (et) > self.timeout:
             raise KeyError
     except KeyError:
         v = _cache[key] = f(*args,**kwargs),time.time()
         if (self.isDebugging):
             print '\n%s :: new (%d) :: "%s"' % (ObjectTypeName.objectSignature(self),len(_cache),key)
     return v[0]
Beispiel #17
0
    def ssh_connect_client(self):
        """ connect and use paramiko Transport to negotiate SSH2 across the connection
	"""
        self.__sftp__ = None
        if (self.transport is None):
            self.__transport__ = self.ssh_connect_transport()
        if (self.__transport__ is not None):
            try:
                self.__sftp__ = paramiko.SFTPClient.from_transport(
                    self.transport)
            except Exception as e:
                exc_info = sys.exc_info()
                info_string = '\n'.join(traceback.format_exception(*exc_info))
                print >> self.lastError, '\n%s :: Cannot open client connection to %s:%s using username of "%s", Reason: %s' % (
                    ObjectTypeName.objectSignature(self), self.hostname,
                    self.port, self.username, info_string)
                try:
                    if (self.sftp is not None):
                        ssh_close()
                except:
                    pass
                return None
        else:
            return None

        return self.sftp
Beispiel #18
0
def asDict(__dict__, insideOut=False, isCopy=False):
    cl = ObjectTypeName.typeClassName(__dict__)
    clName = cl.split('.')[-1]
    dObj = {} if (not isCopy) else eval('%s()' % (clName))
    for k, v in __dict__.iteritems():
        if (insideOut):
            if (isinstance(v, list)):
                for item in v:
                    if (not callable(item)) and (not isDict(item)):
                        dObj[item] = k
            else:
                if (not callable(v)) and (not isDict(v)):
                    dObj[v] = k
        else:
            if (not callable(v)):
                try:
                    if ((callable(v.asDict))):
                        v = v.asDict(isCopy=isCopy, insideOut=insideOut)
                except:
                    pass
                dObj[k] = v
            elif (misc.isList(v)):
                for _i_ in xrange(0, len(v)):
                    if ((callable(v[_i_].asDict))):
                        v[_i_] = v[_i_].asDict(isCopy=isCopy,
                                               insideOut=insideOut)
    return dObj
Beispiel #19
0
    def renderHTML(self, subj, body):
        from vyperlogix.html import myOOHTML as oohtml
        h_html = oohtml.Html()

        if (misc.isString(subj)) and (misc.isList(body)):
            h_html.text(oohtml.oohtml.DOCTYPE_40_TRANSITIONAL)

            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, "Ray C Horn ([email protected])"
            ), (oohtml.oohtml.KEYWORDS, "SMTP Email Message"), (
                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('SMTP Email Message')
            body_html = html_html.tag(oohtml.oohtml.BODY)
            idContent = body_html.tag(oohtml.oohtml.DIV,
                                      id="content",
                                      style="background-color: white")

            idContent.html_simple_table(body)
            pass
        else:
            print >> sys.stderr, '%s :: "subj" parm must be of type str and "body" parm must be of type list rather than of types "%s" and "%s", respectively.' % (
                ObjectTypeName.objectSignature(self), type(subj), type(body))
        return h_html.toHtml()
    def unZipInto(_zip,target,isVerbose=False,callback=None):
	try:
	    iterable = None
	    typ = ObjectTypeName.typeClassName(_zip)
	    if (typ == 'zipfile.ZipFile'):
		iterable = (f.filename for f in _zip.filelist)
	    else:
		raise AttributeError('Invalid _zip attribute cann be of type "%s".' % (typ))
	    if (isVerbose):
		print '*** iterable = %s' % (str(iterable))
	    if (iterable):
		for f in iterable:
		    _f_ = __normalize__(f)
		    fname = os.path.join(target,_f_)
		    if (f.endswith('/')):
			if (not os.path.exists(fname)):
			    os.makedirs(fname)
			if (callable(callback)):
			    try:
				callback(EntityType.folder,f)
			    except:
				pass
		    else:
			__bytes__ = _zip.read(f)
			if (isVerbose):
			    print '%s -> %s [%s]' % (f,fname,__bytes__)
			_utils.writeFileFrom(fname,__bytes__,mode='wb')
			if (callable(callback)):
			    try:
				callback(EntityType.file,f,fname)
			    except:
				pass
	except Exception, _details:
	    if (isVerbose):
		print _utils.formattedException(details=_details)
Beispiel #21
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)))
Beispiel #22
0
 def __init__(self,
              hostname,
              port,
              username,
              password=None,
              use_manual_auth=False,
              callback=None,
              auto_close=True,
              logger=None,
              logPath=os.path.abspath(os.path.dirname(sys.argv[0]))):
     self.__hostname__ = hostname
     self.__port__ = port
     self.__username__ = username
     self.__password__ = password
     self.__transport__ = None
     self.__callback__ = callback
     self.__autoclose__ = auto_close
     self.__logPath__ = logPath
     self.__use_manual_auth__ = use_manual_auth
     self.logger = paramiko.util.get_logger(__name__)
     if (logger):
         self.logger = logger
     else:
         if (self.__logPath__) and (os.path.exists(
                 self.__logPath__)) and (os.path.isdir(self.__logPath__)):
             _utils._makeDirs(self.__logPath__)
             paramiko.util.log_to_file(
                 os.path.join(
                     self.__logPath__,
                     '%s.log' % (ObjectTypeName.objectSignature(self))))
     if self.hostname.find(':') >= 0:
         self.__hostname__, portstr = hostname.split(':')
         self.__port__ = int(portstr)
     self.__open__()
Beispiel #23
0
 def __getitem__(self, name):
     value = super(SmartFuzzyObject, self).__getitem__(name)
     if (value is None):
         raise AttributeError(
             'INVALID use of the method that treats %s as if it were a dictionary.  Try to use this object as if it had instance variables rather than key,value pairs or use the right key name next time.'
             % (ObjectTypeName.objectSignature(self)))
     return value
Beispiel #24
0
 def openProcessForPID(self,pid):
     try:
         procHandle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, 0, pid)
     except Exception as details:
         print '(%s) :: ERROR due to "%s".' % (ObjectTypeName.objectSignature(self),str(details))
         procHandle = None
     return procHandle
Beispiel #25
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))
Beispiel #26
0
 def fget(self):
     _name = 'Log File is NOT Named.'
     _className = ObjectTypeName.typeClassName(self.f)
     if (_className not in ['StringIO.StringIO', 'cStringIO.StringO']):
         try:
             _name = self.f.name
         except AttributeError, details:
             info_string = _utils.formattedException(details=details)
             logging.warning(info_string)
Beispiel #27
0
def openPickledHashBasedOnFilename(filename, method=PickleMethods.none):
    '''Uses the filename to determine which class should be used to open the database file.  Fails with a list if filename has more than one variation present in the same folder.'''
    def deMungeFileName(fname):
        if (isFilenameMungedAlready(fname)):
            toks = fname.split('_')
            if (len(toks) > 2):
                while (len(toks) > 2):
                    toks[0] = '_'.join(toks[0:2])
                    del toks[1]
            _toks = toks[-1].split('.')
            _fname = '.'.join([toks[:len(toks) - 1][0], _toks[-1]])
            _tag = '_' + _toks[0]
            return (fname, _fname, _tag)
        return (None, None)

    dname = os.path.dirname(filename)
    if (len(dname) == 0):
        dname = os.path.abspath('.')
    _obj = None
    _tag = ''
    fname = os.path.basename(filename)
    fname, _fname, _tag = deMungeFileName(fname)
    toks = fname.split('.')
    if (len(toks) > 1):
        toks[-1] = '.' + toks[-1]
    files = [deMungeFileName(f) for f in os.listdir(dname)]
    files = [f[1] for f in files if (f[0] == fname) and (f[-1] == _tag)]
    if (len(files) == 1):
        if (len(_tag) == 0):
            return openPickledHashBasedOnFilename(os.sep.join(
                [dname, files[0]]),
                                                  method=method)
        i = misc.findInListSafely(__classes_tags, _tag)
        if (i > -1):
            info_string = ''
            toks = ObjectTypeName._typeName(__classes[i]).split('.')
            className = toks[len(toks) - 1:][0]
            try:
                s = '%s(filename,method=method)' % (className)
                _obj = eval(s)
            except TypeError:
                try:
                    s = '%s(filename)' % (className)
                    _obj = eval(s)
                except Exception as details:
                    info_string = str(details)
        else:
            raise ValueError(
                '(%s) :: Cannot figure-out the class name based on "%s", recommend working this out on you own because you seemed to have written some bad code or maybe "%s".'
                % (misc.funcName(), _tag, info_string))
    else:
        raise ValueError(
            '(%s) :: Too %s files (%d) named like "%s" %s for %s, recommend using the class name "%s" and open it yourself.'
            % (misc.funcName(), 'many' if (len(files) > 1) else 'few',
               len(files), str(files), str(toks), filename, _tag))
    return _obj
Beispiel #28
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()
Beispiel #29
0
    def put(self, localpath, remotepath, callback=None):
        """
	Copy a local file (localpath) to the SFTP server as remotepath. Any exception raised by operations will be passed through. This method is primarily provided as a convenience.
	
	The SFTP operations use pipelining for speed.
	
	Parameters:
	    * localpath (str) - the local file to copy
	    * remotepath (str) - the destination path on the SFTP server
	    * callback (function(int iBytes, int iTotal, float xfer_rate, int elapsed_secs)) - optional callback function that accepts the bytes transferred so far and the total bytes to be transferred (since 1.7.4)
	
	Returns: SFTPAttributes
	    an object containing attributes about the given file (since 1.7.4) 	
	"""
        import time
        from vyperlogix.misc import _utils

        _begin_ts = time.time()
        _callback_ = None

        def _callback(iBytes, iTotal):
            if (callable(_callback_)):
                et = time.time() - _begin_ts
                if (et == 0):
                    et = 0.00000000001
                xfer = iBytes / et
                try:
                    _callback_(iBytes, iTotal, xfer, et)
                except Exception as details:
                    print >> sys.stderr, '%s' % str(details)

        try:
            if (not callable(callback)):
                callback = None
            else:
                try:
                    callback(0, 0, 0, 0)
                except Exception as details:
                    print >> sys.stderr, '%s :: Cannot use the callback because it has the following problem: "%s".' % (
                        ObjectTypeName.objectSignature(self), str(details))
                    callback = None
            if (callback is not None):
                _callback_ = callback
            result = self.sftp.put(localpath, remotepath, _callback)
            _end_ts = time.time()
            _iTotal = result.st_size
            xfer = _iTotal / (_end_ts - _begin_ts)
            return [result, xfer]
        except:
            exc_info = sys.exc_info()
            info_string = _utils.asMessage('\n'.join(
                traceback.format_exception(*exc_info)))
            print >> sys.stderr, info_string
            return None
        return None
    def perform_login(self,end_point='https://test.salesforce.com/services/Soap/u/14.0',isVerbose=False):
	self.sfContext.login_endpoint = end_point
	try:
	    self.__lastError__ = ''
	    if (isVerbose):
		print '(%s) :: self.username is "%s".' % (ObjectTypeName.objectSignature(self),self.username)
	    if (self.is_running_securely_for_developers):
		print 'self.password is "%s".' % (self.password)
	    if (isVerbose):
		print '(%s) :: self.sfContext.login_endpoint is "%s".' % (ObjectTypeName.objectSignature(self),self.sfContext.login_endpoint)
	    self.__sfdc__ = Connection.connect(self.username, self.password, context=self.sfContext)
	    if (isVerbose):
		print '(%s) :: self.__sfdc__ is "%s".' % (ObjectTypeName.objectSignature(self),self.__sfdc__)
	except Exception as details:
	    info_string = _utils.formattedException(details=details)
	    self.__lastError__ = info_string
	    try:
		del self.__sfdc__
	    finally:
		self.__sfdc__ = None
Beispiel #31
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 #32
0
def get_program_files_registry_values(rootKeyName=__rootKeyName__,
                                      target=__target__):
    values = []
    root = winreg.get_key(winreg.HKEY.LOCAL_MACHINE, rootKeyName,
                          winreg.KEY.ALL_ACCESS)
    targets = SmartObject.SmartFuzzyObject(
        dict([(k, root.values[k]) for k in root.values
              if (str(root.values[k]).find(target) > -1)]))
    for k, v in targets.asDict().iteritems():
        if (ObjectTypeName.typeClassName(v).find('.winreg.REG_SZ') > -1):
            values.append(tuple([k, v]))
    return SmartObject.SmartFuzzyObject(dict(values))
Beispiel #33
0
def create_admin_user(request,parms,browserAnalysis,__air_id__,__apiMap__):
    from g import make_admin_user
    make_admin_user()
    _user = User.objects.get(username=_admin_username)
    ignore = ['_entity','_parent','_password']
    valueOf = lambda v:_utils.getAsSimpleDateStr(v,str(_utils.formatDjangoDateTimeStr())) if (ObjectTypeName.typeClassName(v) == 'datetime.datetime') else str(v) if (v != None) else None
    d = dict([(str(k),valueOf(v)) for k,v in _user.__dict__.iteritems() if (k not in ignore) and (v)])
    d[_air_version_symbol] = air_version[__air_id__]
    if (d[_air_version_symbol] == None):
	d[_api_symbol] = __apiMap__.asMap(noIgnore=True)
    d[_isLoggedIn_symbol] = _user.is_active and _user.is_authenticated() and (not _user.is_anonymous())
    d['REMOTE_ADDR'] = django_utils.get_from_META(request,'REMOTE_ADDR','')
    uname = str(_user)
    u = {
        'id':_user.id, 
        'is_active':_user.is_active, 
        'is_anonymous':_user.is_anonymous(),
        'is_authenticated':_user.is_authenticated(),
        'is_staff':_user.is_staff,
        'is_superuser':_user.is_superuser if (settings.IS_PRODUCTION_SERVER) else (_user.username == settings.SUPER_USER),
        'username':_user.username,
        #'groups':_user._get_groups(),
        #'permissions':_user._get_user_permissions(),
        'name':uname if (len(uname) > 0) else str(_user.username.split('@')[0]).capitalize()
    }
    handle_geolocation(request)
    u = get_starbucks_data(u,_user,__air_id__,parms)
    d[_user_symbol] = u
    json = dict_to_json(d)
    return HttpResponse(content=json,mimetype=__jsonMimetype)