예제 #1
0
    def __call__(self, session=None, form=None):
        self._preCondition(session, form)

        # Get current user
        currentUser = self.lcdb.retrieveUsername(
            session[LCFIT_SESSION_KEY].value)

        # Get a list of forecast/ data objects for that person
        (colNames, objectInfoList) = self.lcdb.listObjectInfo(currentUser)

        # Feed that list into the appropriate template, then in turn into the main navigation template
        searchList = []
        searchList.append({LCFIT_OBJECTLIST_PLACEHOLDER: objectInfoList})
        searchList.append({LCFIT_OBJECTCOLNAMES_PLACEHOLDER: colNames})
        searchList.append({LCFIT_TITLE_PLACEHOLDER: self.title})
        searchList.append(LcConfig)
        objectListTemplate = Template.Template(
            file=self.objectListTemplate,
            searchList=searchList,
            compilerSettings={'prioritizeSearchListOverSelf': True})
        searchList.append(
            {LCFIT_NAV_MAIN_PLACEHOLDER: str(objectListTemplate)})
        pageTemplate = Template.Template(
            file=self.navTemplate,
            searchList=searchList,
            compilerSettings={'prioritizeSearchListOverSelf': True})

        lcfitlogger.debug("LcList: __call__.  User: %s." % currentUser)

        # Write the result
        sys.stdout.write(session.output() + "\n")
        sys.stdout.write('Content-Type: text/html\n\n')
        sys.stdout.write((str(pageTemplate)).strip())
        sys.stdout.flush()
예제 #2
0
    def __call__(self, session, form):
        lcfitlogger.debug('LcForm:  __call__')
        self._preCondition(session, form)

        # set up the templates.  First create the form (inside)
        # template, then pass an expanded str()'ed version of it
        # to navigation (outsided) template in the searchList.  A
        # little bit funky - my apologies.
        searchList = [{
            LCFIT_FORM_TARGET_PLACEHOLDER: self.redirectTarget,
            LCFIT_TITLE_PLACEHOLDER: self.title
        }]
        searchList.append(LcConfig.__dict__)

        formTemplate = Template.Template(
            file=self.formTemplate,
            searchList=searchList,
            compilerSettings={'prioritizeSearchListOverSelf': True})
        searchList.append({LCFIT_NAV_MAIN_PLACEHOLDER: str(formTemplate)})
        pageTemplate = Template.Template(
            file=self.navTemplate,
            searchList=searchList,
            compilerSettings={'prioritizeSearchListOverSelf': True})

        # write and return
        sys.stdout.write(session.output() + "\n")
        sys.stdout.write("Content-Type: text/html\n\n")
        sys.stdout.write(str(pageTemplate).strip())
        sys.stdout.flush()
예제 #3
0
    def __call__(self, session=None, form=None):
        self._preCondition(session, form)
        
        # Get current user
        currentUser = self.lcdb.retrieveUsername(session[LCFIT_SESSION_KEY].value)
            
        # Get a list of forecast/ data objects for that person
        (colNames, objectInfoList) = self.lcdb.listObjectInfo(currentUser)

            # Feed that list into the appropriate template, then in turn into the main navigation template
        searchList = []
        searchList.append({LCFIT_OBJECTLIST_PLACEHOLDER : objectInfoList})
        searchList.append({LCFIT_OBJECTCOLNAMES_PLACEHOLDER : colNames})
        searchList.append({LCFIT_TITLE_PLACEHOLDER:self.title})
        searchList.append(LcConfig)
        objectListTemplate = Template.Template(file=self.objectListTemplate, searchList = searchList,
                                               compilerSettings={'prioritizeSearchListOverSelf' : True})
        searchList.append({LCFIT_NAV_MAIN_PLACEHOLDER : str(objectListTemplate)})
        pageTemplate = Template.Template(file=self.navTemplate, searchList = searchList,
                                         compilerSettings={'prioritizeSearchListOverSelf' : True})
        
        lcfitlogger.debug( "LcList: __call__.  User: %s." % currentUser)
        
        # Write the result
        sys.stdout.write(session.output()+"\n")
        sys.stdout.write('Content-Type: text/html\n\n')
        sys.stdout.write((str(pageTemplate)).strip())
        sys.stdout.flush()
예제 #4
0
	def __init__(self, hmdinput='XXX', start_year='XXX', notes='XXX', **kwargs):
		"""Get beginning state.  Note that some of this code makes it
		possible to instantiate an empty HMD object, to have its
		__dict__ filled from the database."""

		lcfitlogger.debug( 'HMD start')
		if start_year == '':
			raise LcException, "Must enter a start year for HMD Object"
		elif start_year == 'XXX':
			self.start_year = 0
		else:
			self.start_year = LcUtil.parseDate(start_year)
		
		if notes == '':
			raise LcException, "Must enter notes for HMD Object--country at least"
		elif notes == 'XXX':
			self.notes = notes

		self.datapath =	os.path.join(LCFIT_DATADIR, str(random.randint(0, 10**10)))
		
		self.tableString = ''
		self.imagesDict = {}


		if hmdinput == 'XXX':
			return
		else:
			lcfitlogger.debug( 'HMD Stop')
			self.hmdinput = hmdinput
			(self.femaleRates, self.maleRates, self.totalRates) = hmd2lare(hmdinput)
			return
예제 #5
0
    def __call__(self, session=None, form=None):

        self._preCondition(session, form)

        # Retrieve and unpickle an object based on the targetClass
        # name and the instance serial number ...
        try:
            objId= int(form[LCFIT_OBJECT_ID_KEY].value)
        except:
            raise LcException ("can't fine image id") 
        instance = self.lcdb.retrieveObject(objId)

        # ... have said instance draw itself inside the main application
        # template ...
        searchList = []
        searchList.append({LCFIT_NAV_MAIN_PLACEHOLDER : str(instance)})
        searchList.append(LcConfig)
        try:
            searchList.append({LCFIT_TITLE_PLACEHOLDER:self.title})
        except AttributeError:
            searchList.append({LCFIT_TITLE_PLACEHOLDER:'LCFIT Object ID: %i' % objId})
        pageTemplate = Template.Template(file=self.navTemplate, searchList = searchList,
                                         compilerSettings={'prioritizeSearchListOverSelf' : True})

        lcfitlogger.debug( "LcDisplay: __call__.  Object ID:  %s" % objId)

        # test postconditions and return the data 
        sys.stdout.write(session.output() + "\n")
        sys.stdout.write("Content-Type: text/html\n\n")
        sys.stdout.write(str(pageTemplate).strip())
        sys.stdout.flush()
예제 #6
0
    def __call__(self, session=None, form=None):

        self._preCondition(session, form)

        # Retrieve and unpickle an object based on the targetClass
        # name and the instance serial number ...
        try:
            objId = int(form[LCFIT_OBJECT_ID_KEY].value)
        except:
            raise LcException("can't fine image id")
        instance = self.lcdb.retrieveObject(objId)

        # ... have said instance draw itself inside the main application
        # template ...
        searchList = []
        searchList.append({LCFIT_NAV_MAIN_PLACEHOLDER: str(instance)})
        searchList.append(LcConfig)
        try:
            searchList.append({LCFIT_TITLE_PLACEHOLDER: self.title})
        except AttributeError:
            searchList.append(
                {LCFIT_TITLE_PLACEHOLDER: 'LCFIT Object ID: %i' % objId})
        pageTemplate = Template.Template(
            file=self.navTemplate,
            searchList=searchList,
            compilerSettings={'prioritizeSearchListOverSelf': True})

        lcfitlogger.debug("LcDisplay: __call__.  Object ID:  %s" % objId)

        # test postconditions and return the data
        sys.stdout.write(session.output() + "\n")
        sys.stdout.write("Content-Type: text/html\n\n")
        sys.stdout.write(str(pageTemplate).strip())
        sys.stdout.flush()
예제 #7
0
def fitX(func, target, *funcArgs, **funcKwargs):
    """
	e.g. fitX(func=kt2e0, target=77.338912, ax=ax, bx=bx) == 5.  
	"""
    def curryFuncWithTarget(func, target, *funcArgs, **funcKwargs):
        argsP = funcArgs
        kwargsP = funcKwargs

        def f(x):
            return (func(x, *argsP, **kwargsP) - target)**2

        return f

    cf = curryFuncWithTarget(func, target, *funcArgs, **funcKwargs)
    (out, infodict, ier, mesg) = [None] * 4
    try:
        (out, infodict, ier,
         mesg) = scipy.optimize.fsolve(func=cf,
                                       x0=((2 * S.rand()) - 0.5),
                                       full_output=1,
                                       xtol=1.0e-04)
        if ier == 1:
            lcfitlogger.debug("Successful fsolve\n")
        else:
            lcfitlogger.warning("Problem with fsolve. ier = %s, mesg = \"%s.\"\n %s\n" % \
                 (ier, mesg.replace('\n', ' '), infodict))
    except Exception, e:
        lcfitlogger.error(
            "Exception with fsolve: \"%s\".  Catching and ignoring..." % e)
예제 #8
0
 def __call__(self, req):
     req.session = Session(req)
     if req.session.has_key(LCFIT_SESSION_KEY):
         self.lcdb.logout(req.session[LCFIT_SESSION_KEY])
         lcfitlogger.debug( 'LcLogout:  __call__.  Logging out session key: %s' % req.session[LCFIT_SESSION_KEY])
     req.session.invalidate()
     lcfitlogger.warning( 'LcLogout:  __call__.  Logging out unkown session.')
     util.redirect(req, self.redirectTarget)
예제 #9
0
 def __call__(self, req):
     req.session = Session(req)
     if req.session.has_key(LCFIT_SESSION_KEY):
         self.lcdb.logout(req.session[LCFIT_SESSION_KEY])
         lcfitlogger.debug(
             'LcLogout:  __call__.  Logging out session key: %s' %
             req.session[LCFIT_SESSION_KEY])
     req.session.invalidate()
     lcfitlogger.warning(
         'LcLogout:  __call__.  Logging out unkown session.')
     util.redirect(req, self.redirectTarget)
예제 #10
0
 def __call__(self, session, form):
     #self._preCondition(form, session)
     #raise Exception(str(form.keys()))
     objectId = form[LCFIT_OBJECT_ID_KEY].value
     data = self.lcdb.retrieveTextDump(objectSerialNumber=objectId)
     lcfitlogger.debug( "LcDumpText: __call__.  ObjectId: %s."  % objectId)
     sys.stdout.write("Content-type: text/tab-separated-values\n")
     sys.stdout.write("Content-disposition: attachment; filename=forecast-object-%s.txt\n" % objectId)
     sys.stdout.write("Content-length: %i\n\n" % len(data))
     sys.stdout.write(data)
     sys.stdout.flush()
예제 #11
0
 def __call__(self, session, form):
     #self._preCondition(form, session)
     #raise Exception(str(form.keys()))
     objectId = form[LCFIT_OBJECT_ID_KEY].value
     data = self.lcdb.retrieveTextDump(objectSerialNumber=objectId)
     lcfitlogger.debug("LcDumpText: __call__.  ObjectId: %s." % objectId)
     sys.stdout.write("Content-type: text/tab-separated-values\n")
     sys.stdout.write(
         "Content-disposition: attachment; filename=forecast-object-%s.txt\n"
         % objectId)
     sys.stdout.write("Content-length: %i\n\n" % len(data))
     sys.stdout.write(data)
     sys.stdout.flush()
예제 #12
0
    def __call__(self, session=None, form=None):
        """ Deal with registration data"""
        data = f2d(form)

        # Log
        lcfitlogger.debug('LcRegistrationProcess:  __call__')

        ## Clean and check data, display error and return if necessary.
        for k in [
                'USERNAME', 'PASSWORD', 'EMAIL', 'FULLNAME', 'REASONS',
                'HOWFIND', 'AFFILIATION'
        ]:
            if (not data.has_key(k)) or LCFIT_EMPTY_ALL_RE.match(
                    data[k]):  # Error
                err_mess = 'Empty strings or other bad data in form: "%s".<br>Please use the back button and correct.' % (
                    k)
                sl = [{
                    'TITLE': 'Registration Error',
                    'LC_ERROR_MESSAGE': err_mess
                }]
                formTemplate = Template.Template(
                    file=self.errorTemplate,
                    searchList=sl,
                    compilerSettings={'prioritizeSearchListOverSelf': True})
                sys.stdout.write("Content-type: text/html")
                sys.stdout.write(str(formTemplate))
                sys.stdout.flush()
                return (0)
            if k in ('USERNAME', 'PASSWORD'):
                data[k] = re.sub('\s*', '', data[k])
            data[k] = data[k].strip()
            data[k] = data[k].replace("'", "")

        ## Insert info into db (email will be sent by daily sweeper)
        try:
            self.lcdb.insertRegRequest(data)
        except LcException, e:
            lcfitlogger.error('Bad Registration request: %s.' %
                              pprint.pformat(e))
            if re.match('.*pending.*', str(e)):
                sys.stdout.write("Status: 303\nLocation: %s\n\n" %
                                 LCFIT_PREV_PEND_ERROR_PAGE)
                sys.stdout.flush()
            elif re.match('.*in-use.*', str(e)):
                sys.stdout.write("Status: 303\nLocation: %s\n\n" %
                                 LCFIT_PREV_REG_ERROR_PAGE)
                sys.stdout.flush()
            else:
                raise
예제 #13
0
    def __call__(self, session=None, form=None):
        self._preCondition(session, form)

        # Make sure appropriate user, then delete
        currentUser = self.lcdb.retrieveUsername(session[LCFIT_SESSION_KEY].value)
        objectOwner = self.lcdb.retrieveObjectOwner(int(form[LCFIT_OBJECT_ID_KEY].value))
        if currentUser != objectOwner:
            raise LcException("LcDelete: Current user <> object owner")
        else:
            objId = int(form[LCFIT_OBJECT_ID_KEY].value)
            self.lcdb.deleteObject(objId)
            lcfitlogger.debug( "LcDelete: __call__.  Deleted object ID: %s." % objId)
            headers = "Status: 303\nLocation: %s\n\n" % self.redirectTarget
            sys.stdout.write(session.output() + "\n")
            sys.stdout.write(headers)
            sys.stdout.flush()
예제 #14
0
    def __call__(self, session=None, form=None):
        """Handle the page"""

        # Log
        lcfitlogger.debug( 'LcLoginForm:  __call__')

        # Build form ... 
        searchList = []
        searchList.append({'TITLE':self.title})
        searchList.append({'SUBMIT_TARGET': LCFIT_WWW_LOGIN_PROCESS})
        searchList.append(LcConfig.__dict__)

        formTemplate = Template.Template(file=self.formTemplate, searchList = searchList,
                                         compilerSettings={'prioritizeSearchListOverSelf' : True})
        # ... write and return.
        sys.stdout.write("Content-type: text/html\n\n" + str(formTemplate))
        return(0)
예제 #15
0
    def __call__(self, session=None, form=None):
        """Handle the page"""

        # Log
        lcfitlogger.debug('LcLoginForm:  __call__')

        # Build form ...
        searchList = []
        searchList.append({'TITLE': self.title})
        searchList.append({'SUBMIT_TARGET': LCFIT_WWW_LOGIN_PROCESS})
        searchList.append(LcConfig.__dict__)

        formTemplate = Template.Template(
            file=self.formTemplate,
            searchList=searchList,
            compilerSettings={'prioritizeSearchListOverSelf': True})
        # ... write and return.
        sys.stdout.write("Content-type: text/html\n\n" + str(formTemplate))
        return (0)
예제 #16
0
    def __call__(self, session=None, form=None):
        """Handle the page"""

        # Build form from template ... 
        searchList = []
        searchList.append({'TITLE':self.title})
        searchList.append({'SUBMIT_TARGET':LCFIT_WWW_REG_PROCESS}) 
        searchList.append(LcConfig.__dict__)
        formTemplate = Template.Template(file=self.formTemplate, searchList = searchList,
                                                 compilerSettings={'prioritizeSearchListOverSelf' : True})

        # ... log that we are here ...
        lcfitlogger.debug('LcRegistrationForm:  __call__')
        
        # ... write and return.
        sys.stdout.write("content-type:text/html\n\n")
        sys.stdout.write(str(formTemplate))
        sys.stdout.flush()
        return(0)
예제 #17
0
    def __call__(self, session=None, form=None):
        self._preCondition(session, form)

        # Make sure appropriate user, then delete
        currentUser = self.lcdb.retrieveUsername(
            session[LCFIT_SESSION_KEY].value)
        objectOwner = self.lcdb.retrieveObjectOwner(
            int(form[LCFIT_OBJECT_ID_KEY].value))
        if currentUser != objectOwner:
            raise LcException("LcDelete: Current user <> object owner")
        else:
            objId = int(form[LCFIT_OBJECT_ID_KEY].value)
            self.lcdb.deleteObject(objId)
            lcfitlogger.debug("LcDelete: __call__.  Deleted object ID: %s." %
                              objId)
            headers = "Status: 303\nLocation: %s\n\n" % self.redirectTarget
            sys.stdout.write(session.output() + "\n")
            sys.stdout.write(headers)
            sys.stdout.flush()
예제 #18
0
    def __call__(self, session=None, form=None):
        """Handle the page"""

        # Build form from template ...
        searchList = []
        searchList.append({'TITLE': self.title})
        searchList.append({'SUBMIT_TARGET': LCFIT_WWW_REG_PROCESS})
        searchList.append(LcConfig.__dict__)
        formTemplate = Template.Template(
            file=self.formTemplate,
            searchList=searchList,
            compilerSettings={'prioritizeSearchListOverSelf': True})

        # ... log that we are here ...
        lcfitlogger.debug('LcRegistrationForm:  __call__')

        # ... write and return.
        sys.stdout.write("content-type:text/html\n\n")
        sys.stdout.write(str(formTemplate))
        sys.stdout.flush()
        return (0)
예제 #19
0
 def __call__(self, session, form):
     lcfitlogger.debug( 'LcForm:  __call__')
     self._preCondition(session, form)
     
     # set up the templates.  First create the form (inside)
     # template, then pass an expanded str()'ed version of it
     # to navigation (outsided) template in the searchList.  A
     # little bit funky - my apologies.
     searchList = [{LCFIT_FORM_TARGET_PLACEHOLDER : self.redirectTarget,
                    LCFIT_TITLE_PLACEHOLDER:self.title}]
     searchList.append(LcConfig.__dict__)
     
     formTemplate = Template.Template(file=self.formTemplate, searchList = searchList,
                                      compilerSettings={'prioritizeSearchListOverSelf' : True})
     searchList.append({LCFIT_NAV_MAIN_PLACEHOLDER : str(formTemplate)})
     pageTemplate = Template.Template(file=self.navTemplate, searchList = searchList,
                                      compilerSettings={'prioritizeSearchListOverSelf' : True})
     
     # write and return
     sys.stdout.write(session.output() + "\n")
     sys.stdout.write("Content-Type: text/html\n\n")
     sys.stdout.write(str(pageTemplate).strip())
     sys.stdout.flush()
예제 #20
0
파일: LcUtil.py 프로젝트: forkandwait/LCFIT
def fitX(func, target, *funcArgs, **funcKwargs):
	"""
	e.g. fitX(func=kt2e0, target=77.338912, ax=ax, bx=bx) == 5.  
	"""

	def curryFuncWithTarget(func, target, *funcArgs, **funcKwargs):
		argsP = funcArgs
		kwargsP = funcKwargs
		def f(x):
			return (func(x, *argsP, **kwargsP) - target)**2
		return f 
	cf = curryFuncWithTarget(func, target, *funcArgs, **funcKwargs)
	(out, infodict, ier, mesg) = [None]*4
	try:
		(out, infodict, ier, mesg) = scipy.optimize.fsolve(
			func=cf, x0=((2*S.rand())-0.5), full_output=1, xtol=1.0e-04)
		if ier == 1:
			lcfitlogger.debug( "Successful fsolve\n")
		else:
			lcfitlogger.warning("Problem with fsolve. ier = %s, mesg = \"%s.\"\n %s\n" % \
						  (ier, mesg.replace('\n', ' '), infodict))
	except Exception, e:
		lcfitlogger.error( "Exception with fsolve: \"%s\".  Catching and ignoring..." % e)
예제 #21
0
    def __init__(self,
                 hmdinput='XXX',
                 start_year='XXX',
                 notes='XXX',
                 **kwargs):
        """Get beginning state.  Note that some of this code makes it
		possible to instantiate an empty HMD object, to have its
		__dict__ filled from the database."""

        lcfitlogger.debug('HMD start')
        if start_year == '':
            raise LcException, "Must enter a start year for HMD Object"
        elif start_year == 'XXX':
            self.start_year = 0
        else:
            self.start_year = LcUtil.parseDate(start_year)

        if notes == '':
            raise LcException, "Must enter notes for HMD Object--country at least"
        elif notes == 'XXX':
            self.notes = notes

        self.datapath = os.path.join(LCFIT_DATADIR,
                                     str(random.randint(0, 10**10)))

        self.tableString = ''
        self.imagesDict = {}

        if hmdinput == 'XXX':
            return
        else:
            lcfitlogger.debug('HMD Stop')
            self.hmdinput = hmdinput
            (self.femaleRates, self.maleRates,
             self.totalRates) = hmd2lare(hmdinput)
            return
예제 #22
0
 def __call__(self, session=None, form=None):
     """ Deal with registration data"""
     data = f2d(form)    
     
     # Log
     lcfitlogger.debug( 'LcRegistrationProcess:  __call__')
     
     ## Clean and check data, display error and return if necessary.
     for k in ['USERNAME', 'PASSWORD', 'EMAIL', 'FULLNAME', 'REASONS', 'HOWFIND', 'AFFILIATION']:
         if (not data.has_key(k)) or LCFIT_EMPTY_ALL_RE.match(data[k]): # Error
             err_mess = 'Empty strings or other bad data in form: "%s".<br>Please use the back button and correct.' % (k)
             sl = [{'TITLE':'Registration Error','LC_ERROR_MESSAGE':err_mess}]
             formTemplate = Template.Template(file=self.errorTemplate, searchList = sl,
                                              compilerSettings={'prioritizeSearchListOverSelf' : True}) 
             sys.stdout.write("Content-type: text/html")
             sys.stdout.write(str(formTemplate))
             sys.stdout.flush()
             return(0)
         if k in ('USERNAME', 'PASSWORD'):
             data[k] = re.sub('\s*', '', data[k]) 
         data[k] = data[k].strip()
         data[k] = data[k].replace("'", "")
         
     ## Insert info into db (email will be sent by daily sweeper)
     try:
         self.lcdb.insertRegRequest(data)
     except LcException, e:
         lcfitlogger.error( 'Bad Registration request: %s.' % pprint.pformat(e))
         if re.match('.*pending.*', str(e)):
             sys.stdout.write("Status: 303\nLocation: %s\n\n" %  LCFIT_PREV_PEND_ERROR_PAGE)
             sys.stdout.flush()
         elif re.match('.*in-use.*', str(e)):
             sys.stdout.write("Status: 303\nLocation: %s\n\n" %  LCFIT_PREV_REG_ERROR_PAGE)
             sys.stdout.flush()
         else:
             raise