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
Example #2
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
Example #3
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
Example #4
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.')
    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)
Example #6
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
Example #7
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()
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
Example #9
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)
Example #10
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))
Example #11
0
def get_package_details2(browser, _url, url, logging=None):
    import urllib2
    from vyperlogix.misc import ObjectTypeName
    from vyperlogix import misc

    req = urllib2.Request(url)
    req.add_header("Referer", url.split('?')[0])
    browser.open(req)

    d = lists.HashedLists2()

    _forms = []
    for form in browser.forms():
        elements = form.controls
        _forms.append(tuple([len(elements), elements]))
    d_forms = dict(_forms)
    keys = misc.sort(d_forms.keys())
    elements = d_forms[keys[-1]]
    if (len(elements) > 0):
        inputs = [
            c for c in [(ele, ObjectTypeName.typeClassName(ele))
                        for ele in elements]
            if (c[-1].find('ClientForm.') > -1) and (
                c[-1] not in ['ClientForm.SubmitControl'])
        ]
        for item in inputs:
            ele, cname = item
            d_attrs = ele.attrs
            if (cname == 'ClientForm.SelectControl'):
                choice = [
                    choice for choice in ele.get_items() if (choice._selected)
                ]
                d[d_attrs['name']] = ','.join([
                    a['label'] for a in [
                        choice.attrs for choice in ele.get_items()
                        if (choice._selected)
                    ]
                ])
            elif (cname == 'ClientForm.TextareaControl'):
                for p in ele.pairs():
                    d[p[0]] = p[-1]
            else:
                try:
                    d[d_attrs['name']] = d_attrs['value']
                except Exception as e:
                    info_string = _utils.formattedException(details=e)
                    pass
        return d, form.attrs
    return d, []
Example #12
0
def getZipFilesAnalysis2(_zip):
    import os
    from vyperlogix.misc import ObjectTypeName
    from vyperlogix.hash import lists

    _analysis = lists.HashedLists2()
    try:
        iterable = None
        if (ObjectTypeName.typeClassName(_zip) == 'zipfile.ZipFile'):
            iterable = (f.filename for f in _zip.filelist)
        elif (lists.isDict(_zip)):
            iterable = (f for f in _zip.keys())
        for f in iterable:
            _analysis[f] = f
    except:
        pass
    return _analysis
Example #13
0
def render_from_string(source, context={}):
    from django.template import Context
    from django.template import loader
    from django.template.loader import get_template

    _content = ''
    tplate = source
    if (misc.isString(source)):
        tplate = loader.get_template_from_string(source)
    toks1 = ObjectTypeName.typeClassName(tplate).split('.')
    toks2 = 'django.template.Template'.split('.')
    cnt = 0
    for t in toks2:
        if (t in toks1):
            cnt += 1
    if (cnt == len(toks2)):
        _content = tplate.render(Context(context, autoescape=False))
    return _content
Example #14
0
def get_tabs_nav_html(navigation_tabs, request=None, content=''):
    h = oohtml.Html()
    ul = h.tag(oohtml.oohtml.UL)
    i = 1
    request_path = request.path if (ObjectTypeName.typeClassName(request).find(
        'django.core.handlers.wsgi.WSGIRequest') > -1) else ''
    for tab in navigation_tabs:
        _url, _text1, _text2 = tab
        ul._tagLI(
            oohtml.renderAnchor('%s' % _url,
                                _text1,
                                target="_blank" if
                                (_url.find('://') > -1) else "_top",
                                rel='sb%d' % i,
                                class_='selected' if
                                (_url == request_path) else ''))
        i += 1
    ul._tagLI(content if (misc.isString(content)) else '')

    return h.toHtml()
Example #15
0
def unZipInto(_zip, target, isVerbose=False, callback=None):
    import os
    from vyperlogix.misc import ObjectTypeName
    from vyperlogix.hash import lists
    from vyperlogix.misc import _utils

    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_ = f.replace('/', os.sep)
                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 as _details:
        if (isVerbose):
            print _utils.formattedException(details=_details)
Example #16
0
 def __init__(self,
              fileName,
              method=PickleMethods.useBsdDbShelf,
              has_bsddb=False):
     _isProperType = lambda obj: (ObjectTypeName.typeClassName(obj).find(
         'Enum.EnumInstance') > -1)
     isProperType = _isProperType(method)
     _isProperValue = lambda obj: (
         (obj.value & PickleMethods.useBsdDbShelf.value) != 0)
     isProperValue = False
     if (isProperType):
         isProperValue = _isProperValue(method)
     if (not isProperType) or (not isProperValue):
         if (not isProperType):
             method = PickleMethods.useBsdDbShelf
             isProperValue = _isProperValue(method)
         if (not isProperValue):
             method |= PickleMethods.useBsdDbShelf
     return super(PickledHash2, self).__init__(fileName,
                                               method,
                                               has_bsddb=has_bsddb)
Example #17
0
def getZipFilesAnalysis(_zip, prefix='', _acceptable_types=[]):
    import os
    from vyperlogix.misc import ObjectTypeName
    from vyperlogix.hash import lists

    _analysis = lists.HashedLists()
    try:
        iterable = None
        if (ObjectTypeName.typeClassName(_zip) == 'zipfile.ZipFile'):
            iterable = (f.filename for f in _zip.filelist)
        elif (lists.isDict(_zip)):
            iterable = (f for f in _zip.keys())
        for f in iterable:
            toks = os.path.splitext(f)
            if (len(_acceptable_types) == 0) or (
                    toks[-1].split('.')[-1]
                    in _acceptable_types) or ((len(prefix) > 0) and
                                              (toks[0].startswith(prefix))):
                _analysis[toks[0]] = toks[-1] if (len(toks) > 1) else ''
    except:
        pass
    return _analysis
Example #18
0
    def walk_nodes(self, url, callback=None):
        self.referer = url
        self.request = urllib2.Request(url)
        self.request.add_header("Referer", self.referer)
        self.browser.open(self.request)
        c = self.browser.response().read()
        self.soup = BeautifulStoneSoup(c)

        try:
            item_nodes = self.soup.findAll("item")
            for item in item_nodes:
                so = SmartObject.SmartObject()
                for node in item.recursiveChildGenerator():
                    if (ObjectTypeName.typeClassName(node)
                            == 'BeautifulSoup.Tag') and (node.string):
                        so[node.name] = _utils.ascii_only(
                            node.string.extract())
                if (callable(callback)):
                    callback(so)
        except Exception as e:
            info_string = _utils.formattedException(details=e)
            so = SmartObject.SmartObject()
            s.info_string = info_string
            items.append(so)
Example #19
0
def isRePattern(obj):
    from vyperlogix.misc import ObjectTypeName
    try:
        return ObjectTypeName.typeClassName(obj) == '_sre.SRE_Pattern'
    except TypeError:
        return False
        def fget(self):
	    isUsernameValid = misc.isString(self.username)
	    isPasswordValid = misc.isString(self.password)
	    isSFDCValid = (self.sfdc is not None) and (ObjectTypeName.typeClassName(self.sfdc).find('pyax.connection.Connection') > -1)
            return (isUsernameValid) and (isPasswordValid) and (isSFDCValid)
Example #21
0
    def process_request(self, request):
        url_toks = django_utils.parse_url_parms(request)

        http_host = request.META['HTTP_X_FORWARDED_SERVER'] if (
            request.META.has_key('HTTP_X_FORWARDED_SERVER')
        ) else request.META['HTTP_HOST']
        _host = http_host.split(':')[0]

        s = 'combined%s.settings' % ('.django' if (
            not django_utils.isProduction(django_utils._cname)) else '')
        m = LazyImport.LazyImport(s)
        m = m.__lazyimport_import
        settings._target = None
        settings.configure(**m.__dict__)

        d = lists.HashedLists2(
            dict([(k, v) for k, v in m.__dict__.iteritems()
                  if (not k.startswith('__')) and (not k.endswith('__')) and (
                      ObjectTypeName.typeClassName(v) != 'module')]))
        if (django_utils.isBeingDebugged) and (sys.platform != 'win32'):
            fout = open('/home/raychorn/debug.txt', 'w')
            try:
                print >> fout, '_host is "%s".' % (_host)
                print >> fout, '%s\n' % ('=' * 80)
                d.prettyPrint(title=s, fOut=fout)
            finally:
                fout.flush()
                fout.close()

        r_url = settings.ROOT_URLCONF

        isAdjustingInstalledApps = False
        if (settings.SITES.has_key(_host)):
            aSite = settings.SITES[_host]
            s = '%s.settings' % (aSite.__name__)
            m = LazyImport.LazyImport(s)
            m = m.__lazyimport_import

            d = dict([
                (k, v) for k, v in m.__dict__.iteritems()
                if (not k.startswith('__')) and (not k.endswith('__')) and (
                    ObjectTypeName.typeClassName(v) != 'module')
            ])
            if (d.has_key('INSTALLED_APPS')):
                d['INSTALLED_APPS'] = self.__adjust_apps__(
                    d['INSTALLED_APPS'], aSite)
                m.__dict__['INSTALLED_APPS'] = d['INSTALLED_APPS']
            request.session['settings'] = d

            settings._target = None
            settings.configure(**m.__dict__)

            d = lists.HashedLists2(
                dict([(k, v) for k, v in m.__dict__.iteritems()
                      if (not k.startswith('__')) and (not k.endswith('__'))
                      and (ObjectTypeName.typeClassName(v) != 'module')]))

            _path = aSite.__path__[0]

            x = ListWrapper.ListWrapper(sys.path)
            xi = x.findAllMatching(_path)
            if (len(xi) == 0):
                sys.path.insert(0, _path)

            isAdjustingInstalledApps = True
            settings.ROOT_URLCONF = '%s.%s' % (
                aSite.__name__, settings.ROOT_URLCONF.split('.')[-1])
        else:
            settings.ROOT_URLCONF = s.replace('.settings', '.urls')

        _app_loader_errors = []
        if (settings.INSTALLED_APPS):
            loading._loaded = False
            loading._app_list = []
            loading._app_models = {}
            for app in settings.INSTALLED_APPS:
                try:
                    aModule = loading.load_app(app)
                    app_name = app.split('.')[-1]
                    if (aModule is not None) and (
                            not loading._app_models.has_key(app_name)):
                        reload(aModule)
                except ImportError, e:
                    if (str(e).find('No module named') == -1):
                        _app_loader_errors.append(
                            _utils.formattedException(details=e))
            loading._loaded = True
Example #22
0
THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !

USE AT YOUR OWN RISK.
"""

real_k = lambda foo: str(foo) if (foo is None) else foo[
    0 if not foo.startswith('__') else 2:len(foo)
    if not foo.endswith('__') else len(foo) - 2]

isSmartObject = lambda obj: ObjectTypeName.typeClassName(obj).find(
    '.SmartObject') > -1


def asPythonDict(obj):
    try:
        return obj.asPythonDict()
    except:
        try:
            return obj.asDict(cls=dict)
        except:
            pass
    return obj


class SmartObject(Cooperative):
    def __init__(self, args={}):
Example #23
0
 def is_ModelChoiceField(self, obj):
     return (
         ObjectTypeName.typeClassName(obj).find('models.ModelChoiceField') >
         -1)
Example #24
0
    def __crontab__(config,
                    jsonHandler=jsonHandler,
                    callback=callback,
                    logging_callback=logging_callback,
                    default=default):
        __lines__ = ''

        __logger__(
            'INFO.1.1: verbose="%s" (%s).' %
            (config.verbose, ObjectTypeName.typeClassName(config.verbose)))
        try:
            __logger__('INFO.1.2: config="%s".' % (config))
            if (config.verbose):
                __logger__('INFO.1.3: JSON FPath ?: "%s".' %
                           (config.jsonFpath))
            if (callable(jsonHandler)):
                try:
                    __config__ = jsonHandler(config.jsonFpath)
                except Exception as ex:
                    __config__ = SmartObject()
            __file__ = config.schedulefpath if (misc.isStringValid(
                config.schedulefpath)) else None
            if (config.verbose):
                __logger__('INFO.1.4: Crontab ?: "%s".' % (__file__))
            if (os.path.exists(__file__)):
                if (config.verbose):
                    __logger__('INFO.1.5: Crontab Exists: "%s".' % (__file__))
                __lines__ = _utils._readFileFrom(__file__)
                if (config.verbose):
                    __logger__('INFO.1.6: Crontab Content: "%s".' %
                               (__lines__))
        except Exception as ex:
            __logger__('EXCEPTION.1: "%s".' %
                       (_utils.formattedException(details=ex)))

        __logger__('INFO.1.6.1: config.isRunning="%s".' % (config.isRunning))
        while (config.isRunning and threaded):
            jobs = [
                CronExpression(__line__) for __line__ in normalize(__lines__)
                if (misc.isStringValid(__line__))
            ]
            config.isRunning = callback(jobs) if (callable(callback)) else True
            if (config.isRunning):
                for job in jobs:
                    if (config.verbose):
                        __logger__('INFO.1.7: Job: "%s".' % (job))
                    if job.check_trigger(time.gmtime(time.time())[:5]):
                        if (config.dryrun):
                            __logger__('INFO.1.8: Execute: %s' % (job.comment))
                        else:
                            import tempfile
                            __cmd__ = tempfile.NamedTemporaryFile().name
                            __sysout__ = _utils.stringIO()

                            def __callback__(ss, data=None):
                                global __begin__
                                if (data) and (misc.isString(data)) and (
                                        len(data) > 0):
                                    __logger__('INFO.1.9: %s' % (data))
                                return

                            def __onExit__(ss):
                                __logger__('INFO.1.10: __onExit__')
                                __logger__('INFO.1.11: %s' %
                                           (__sysout__.getvalue()))
                                if (os.path.exists(__cmd__)):
                                    os.remove(__cmd__)

                            wfHandle = open(__cmd__, 'w')
                            print >> wfHandle, '@echo on\n'
                            print >> wfHandle, '%s\n' % (job.comment)
                            wfHandle.flush()
                            wfHandle.close()
                            ss = SmartShell(__cmd__,
                                            callback=__callback__,
                                            isDebugging=True,
                                            onExit=__onExit__,
                                            sysout=__sysout__)
                            ss.execute()

                if (threaded):
                    if (config.verbose):
                        __logger__('INFO.1.12: Sleeping for %s secs...' %
                                   (config.resolution))
                    time.sleep(config.resolution if (
                        isinstance(config.resolution, float)
                        or isinstance(config.resolution, int)) else 60)

                    if (callable(jsonHandler)):
                        try:
                            __config__ = jsonHandler(config.jsonFpath)
                        except Exception as ex:
                            __config__ = SmartObject()
                    __file__ = config.schedulefpath if (misc.isStringValid(
                        config.schedulefpath)) else None
                    if (os.path.exists(__file__)):
                        if (config.verbose):
                            __logger__('INFO.1.13: Crontab Exists: "%s".' %
                                       (__file__))
                        __lines__ = _utils._readFileFrom(__file__)
                        if (config.verbose):
                            __logger__('INFO.1.14: Crontab Content: "%s".' %
                                       (__lines__))
        else:
            __logger__(
                'WARNING.1.15: Cannot execute crontab unless threaded is %s (true).'
                % (threaded))
        return config.isRunning
Example #25
0
def admob_ad(request, admob_params=HashedFuzzyLists2()):
    """
	Given a Django ``request`` object and dict of
	admob parameters returns a Admob ad.

	If no ad can be retrieved displays a one pixel
	Admob tracker image.

	Usage:

	def my_view(request):

		admob_dict = {}
		admob_dict["admob_site_id"] = "required_admob_site_id"
		admob_dict["admob_postal_coode"] = "optional_postal_code"
		admob_dict["admob_area_code"] = "optional_area_code"
		admob_dict["admob_coordinates"] = "optional_coordinates"
		admob_dict["admob_gender"] = "optional_gender"
		admob_dict["admob_keywords"] = "optional_keywords"
		admob_dict["admob_search"] = "optional_search"		
		admob_dict["admob_mode"] = "test" # leave this out for the live site...

		ad = admob_ad(request, admob_dict)

		return HttpResponse(ad)

	"""
    from vyperlogix.misc import ObjectTypeName
    _type = ObjectTypeName.typeClassName(admob_params)
    if (_type.find('vyperlogix.hash.lists.HashedFuzzyLists2') == -1):
        admob_params = HashedFuzzyLists2(fromDict=admob_params)
    # Change to "live" when ready to deploy.
    admob_mode = "test" if (admob_params["admob_mode"] == 'test') else None

    admob_endpoint = "http://r.admob.com/ad_source.php"
    admob_version = "20080714-PYTHON"
    admob_timeout = 1.0
    admob_ignore = (
        "HTTP_PRAGMA",
        "HTTP_CACHE_CONTROL",
        "HTTP_CONNECTION",
        "HTTP_USER_AGENT",
        "HTTP_COOKIE",
    )

    # Build URL.
    admob_post = {}

    # Required Parameters - will raise if not found.
    admob_post["s"] = admob_params["admob_site_id"]

    # Meta Parameters.
    admob_post["u"] = request.META.get("HTTP_USER_AGENT", None)
    admob_post["i"] = request.META.get("REMOTE_ADDR", None)
    admob_post["p"] = request.build_absolute_uri()
    admob_post["t"] = md5(request.session.session_key).hexdigest()

    # Hardcoded Parameters.
    admob_post["e"] = "UTF-8"
    admob_post["v"] = admob_version

    # Optional Parameters.
    admob_post["ma"] = admob_params["admob_markup"]
    admob_post["d[pc]"] = admob_params["admob_postal_code"]
    admob_post["d[ac]"] = admob_params["admob_area_code"]
    admob_post["d[coord]"] = admob_params["admob_coordinates"]
    admob_post["d[dob]"] = admob_params["admob_dob"]
    admob_post["d[gender]"] = admob_params["admob_gender"]
    admob_post["k"] = admob_params["admob_keywords"]
    admob_post["p"] = admob_params["admob_siteID"]
    admob_post["search"] = admob_params["admob_search"]

    for k, v in request.META.items():
        if k not in admob_ignore:
            admob_post["h[%s]" % k] = v

    # Strip all ``None`` and empty values from admob_post.
    for k, v in admob_post.items():
        if v is None or v == "":
            admob_post.pop(k)

    if admob_mode == "test":
        admob_post["m"] = "test"

    # Request the Ad.
    admob_success = True
    try:
        admob_data = urlencode(admob_post)
        admob_file = urlopen(admob_endpoint, admob_data)
        admob_contents = admob_file.read()
        if admob_contents is None or admob_contents == "":
            admob_success = False
    except Exception as e:
        admob_success = False

    if not admob_success:
        if (admob_params["alternate_content"]):
            admob_contents = admob_params["alternate_content"]
        else:
            admob_contents = "<img src=\"http://t.admob.com/li.php/c.gif/%(admob_site_id)s/1/%(admob_timeout)F/%(absolute_uri)s\" alt=\"\" width=\"1\" height=\"1\" />"  \
                        % {"admob_site_id" : admob_params["admob_site_id"],
                           "admob_timeout" : admob_timeout,
                           "absolute_uri" : md5(request.build_absolute_uri()).hexdigest()}

    # DEBUG:
    # print 'Connecting to: %s' % admob_endpoint
    # print 'Sending Parameters:'
    # print admob_post
    # print 'Got reponse:'
    # print admob_contents

    return admob_contents
Example #26
0
 def fget(self):
     return ObjectTypeName.typeClassName(self)
Example #27
0
 def is_BooleanField(self, obj):
     return (ObjectTypeName.typeClassName(obj).find('fields.BooleanField') >
             -1)
Example #28
0
 def write(self, s):
     _typeName = ObjectTypeName.typeClassName(self.fOut)
     if (_typeName.find('.EchoLog') == -1):
         print >> self.fOut, s.strip()
     super(EchoLog, self).write(s)
Example #29
0
def grid_handler(request, cls_or_object, func=None):
    '''
    request is the Django Request,
    cls_or_object is the Django Model class or a model object or list of model objects
    func is a callable that takes a row and returns a list of items in the proper order for the grid.'''
    import math
    import simplejson

    from vyperlogix.misc import _utils

    from vyperlogix.django import django_utils
    from vyperlogix.misc import ObjectTypeName

    page = django_utils.get_from_post_or_get(request, 'page', default=-1)
    rows = django_utils.get_from_post_or_get(request, 'rows', default=-1)
    sidx = django_utils.get_from_post_or_get(request, 'sidx', default='')
    sord = django_utils.get_from_post_or_get(request, 'sord', default='')

    try:
        if sidx == '': sidx = 1

        symbol_ModelBase = 'django.db.models.base.ModelBase'
        symbol_QuerySet = 'django.db.models.query.QuerySet'
        class_ = ObjectTypeName.typeClassName(cls_or_object)
        if (class_ in [symbol_ModelBase, symbol_QuerySet]):
            try:
                items = cls_or_object.objects.order_by(sidx) if (
                    class_
                    == symbol_ModelBase) else cls_or_object.order_by(sidx)
                if sord == 'desc':
                    items = misc.reverse(items)
            except Exception as details:
                info_string = _utils.formattedException(details=details)
                print >> sys.stderr, info_string
        elif (isinstance(cls_or_object, list)):
            try:
                items = cls_or_object
            except Exception as details:
                info_string = _utils.formattedException(details=details)
                print >> sys.stderr, info_string
        else:
            try:
                items = [cls_or_object]
            except Exception as details:
                info_string = _utils.formattedException(details=details)
                print >> sys.stderr, info_string

        count = len(items)
        total_pages = int(math.ceil(count / rows)) if (count > 0) else 1
        total_pages = total_pages if (total_pages > 0) else 1

        if (page > total_pages):
            page = total_pages
        start = (rows * page) - rows

        start = 0 if (start < 0) else start

        cells = [func(r) if (callable(func)) else r for r in items[start:rows]]
        results = [{'cell': c} for c in cells]
    except Exception as details:
        results = []
        count = _real_count(results)
        info_string = _utils.formattedException(details=details)
        print >> sys.stderr, info_string

    ret = {
        'page': page,
        'total': total_pages,
        'records': count,
        'rows': results
    }
    return simplejson.dumps(ret)
Example #30
0
    def validate_and_save(self,
                          request,
                          d_context,
                          callback=None,
                          callback_beforeSave=None,
                          callback_validation_failed=None,
                          callback_error=None):
        self.__last_error__ = ''
        for field_name in request.POST.keys():
            if (self.fields.has_key(field_name)):
                aField = self.fields[field_name]
                aField.value = request.POST[field_name]
                if (aField.required):
                    if (self.is_CharField(aField)):
                        if (len(aField.value.strip()) < aField.min_length if
                            (aField.min_length) else 1):
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    '&nbsp;%s requires at least %d chars.' %
                                    (aField.label, aField.min_length if
                                     (aField.min_length is not None) else 0),
                                    class_='error')
                    elif (self.is_EmailField(aField)):
                        valid_email = validateEmail(aField.value)
                        valid_email_domain = True  # Assume the domain is valid so long as the domain name appears to be valid in case there is no other filter.
                        email_domain = aField.value.split('@')[-1]
                        if (callable(
                                self.get_freehost_by_name)) and (valid_email):
                            hosts = self.get_freehost_by_name(email_domain)
                            valid_email_domain = (hosts is None) or (
                                (misc.isList(hosts)) and (len(hosts) == 0))
                        if (not valid_email) or (not valid_email_domain):
                            extra_msg = ' because "%s" is not an allowed domain' % (
                                email_domain) if (
                                    not valid_email_domain) else ''
                            d_context['ERROR_%s' % (field_name.upper(
                            ))] = oohtml.render_SPAN(
                                '&nbsp;Please enter a valid internet email address%s.'
                                % (extra_msg),
                                class_='error')
                    elif (self.is_ModelChoiceField(aField)):
                        can_consisder_validation = True
                        for validation_tuple in self.__field_validations__:
                            if (callable(validation_tuple[0])):
                                if (validation_tuple[-1].has_key(field_name)):
                                    can_consisder_validation = False
                        if (can_consisder_validation):
                            if (len(aField.value) == 0):
                                d_context[
                                    'ERROR_%s' %
                                    (field_name.upper())] = oohtml.render_SPAN(
                                        '&nbsp;Selection for %s is not valid.'
                                        % (aField.label),
                                        class_='error')
                        if (len(aField.value) > 0):
                            kw = {
                                self.get_choice_model_for_field_by_name(field_name).value_id:
                                aField.value
                            }
                            aField._value = aField.queryset.filter(**kw)[0]
                    elif (self.is_BooleanField(aField)):
                        isError = False
                        try:
                            aField.value = eval(aField.value)
                        except Exception as e:
                            isError = True
                            info_string = _utils.formattedException(details=e)
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    '<BR/>'.join(info_string.split('\n')),
                                    class_='error')
                            aField.value = False
                        if (not isError) and (not isinstance(
                                aField.value, bool)):
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    'Not a valid Boolean value.',
                                    class_='error')
                    elif (self.is_DateTimeField(aField)):
                        isError = False
                        try:
                            aField.value = _utils.getFromDateTimeStr(
                                aField.value,
                                format=_utils.formatDate_MMDDYYYY_slashes())
                        except Exception as e:
                            isError = True
                            info_string = _utils.formattedException(details=e)
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    '<BR/>'.join(info_string.split('\n')),
                                    class_='error')
                            aField.value = None
                        if (not isError) and (ObjectTypeName.typeClassName(
                                aField.value) != 'datetime.datetime'):
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    'Not a valid DateTime value.',
                                    class_='error')
            else:
                pass
        for validation_tuple in self.__field_validations__:
            if (callable(validation_tuple[0])):
                if (validation_tuple[0](self)):
                    for k, v in validation_tuple[-1].iteritems():
                        d_context['ERROR_%s' %
                                  (k.upper())] = oohtml.render_SPAN(
                                      '&nbsp;%s' % (v), class_='error')

        if (len(d_context) > 0):
            for field_name in request.POST.keys():
                if (self.fields.has_key(field_name)):
                    aField = self.fields[field_name]
                    aField.value = request.POST[field_name]
                    d_context['VALUE_%s' % (field_name.upper())] = aField.value
            if (callable(callback_validation_failed)):
                return callback_validation_failed(self, d_context)
        else:
            lable_from_field = lambda foo: f.label if (not misc.isString(f)
                                                       ) else f
            try:
                pk = self.model._meta.pk
                try:
                    kw = {
                        lable_from_field(pk.formfield()): [
                            f for f in self.fields if (lable_from_field(
                                f) == lable_from_field(pk.formfield()))
                        ][0]
                    }
                except:
                    url_toks = django_utils.parse_url_parms(request)
                    kw = {
                        pk.column:
                        int(url_toks[-1]) if
                        (str(url_toks[-1]).isdigit()) else -1
                    }
                anObj = self.model.objects.get(**kw)
            except Exception as details:
                anObj = self.model()

            for field_name, aField in self.fields.iteritems():
                try:
                    if self.is_ModelChoiceField(aField):
                        anObj.__setattr__(field_name, aField._value)
                    else:
                        anObj.__setattr__(field_name, aField.value)
                except Exception as e:  # ignore all the hidden fields or any other fields for which there is no data present.
                    info_string = _utils.formattedException(details=e)
            for k, v in self.__extra_fields__.iteritems():
                try:
                    anObj.__setattr__(k, v)
                except Exception as e:
                    info_string = _utils.formattedException(details=e)
            if (callable(callback_beforeSave)):
                callback_beforeSave(self, request, anObj)
            try:
                anObj.save()
            except Exception as details:
                self.__last_error__ = _utils.formattedException(
                    details=details)
                if (callable(callback_error)):
                    callback_error(self, request)
            finally:
                if (len(self.last_error) > 0):
                    if (callable(callback_validation_failed)):
                        return callback_validation_failed(self, d_context)
                else:
                    if (callable(callback)):
                        return callback(self, request)
        return None
Example #31
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)
Example #32
0
 def is_DateTimeField(self, obj):
     return (ObjectTypeName.typeClassName(obj).find('fields.DateTimeField')
             > -1)
Example #33
0
 def is_EmailField(self, obj):
     return (ObjectTypeName.typeClassName(obj).find('fields.EmailField') >
             -1)