• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python string.capitalize函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中string.capitalize函数的典型用法代码示例。如果您正苦于以下问题:Python capitalize函数的具体用法?Python capitalize怎么用?Python capitalize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了capitalize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: gen_entity_def

def gen_entity_def(module, folder, settings):
    #mapper
    fname = os.path.join(folder, string.capitalize(module['name']) + 'Mappers.java')
    kwargs = {}
    kwargs.update(settings)
    kwargs['now'] = datetime.now()
    kwargs['_module_'] = module['name']
    kwargs['_moduleC_'] = string.capitalize(module['name'])
    kwargs['_entitys_'] = []
    for tbl in module['tables']:
        kwargs['_entitys_'].append(dbm.java_name(tbl))
    javagen.render_mapper(fname, **kwargs)
    kwargs.pop('_entitys_')
    #entity and service
    for tbl in module['tables']:
        tbi = dbm.get_table(module, tbl)
        kwargs['_tbi_'] = tbi
        fname = os.path.join(folder, tbi.entityName + '.java')
        kwargs['_cols_'] = tbi.columns
        kwargs['_pks_'] = tbi.pks
        #entity
        javagen.render_entity(fname, **kwargs)
        fname = os.path.join(folder, 'service', tbi.entityName + 'Tx.java')
        #db-tx
        javagen.render_tx(fname, **kwargs)
开发者ID:343829084,项目名称:argo,代码行数:25,代码来源:entity_gen.py


示例2: list_data

def list_data(table, filename='to-do.db'):
    '''List all data.'''
    category_name = table
    conn = sqlite3.connect(filename)
    c = conn.cursor()
    if table == None:
        # Get all category names.
        table = c.execute('''SELECT name FROM sqlite_master
                            WHERE type='table'
                            ORDER BY name''')
        for category in table:
            list_data(category[0])
    else:
        try:
            table = c.execute('''SELECT * FROM %s''' % table)
        except sqlite3.OperationalError:
            print 'The category "%s" does not exist.' % table
            sys.exit()
        print string.capitalize(category_name)
        for row in table:
            if row[0]:
                head = to_unicode(row[0])
                print '  - ' + string.capitalize(str(head))
                if row[1]:
                    tail = to_unicode(row[1])
                    print '    ' + string.capitalize(str(tail))
        print
开发者ID:hph,项目名称:rem,代码行数:27,代码来源:rem.py


示例3: addBooks

  def addBooks(self,booksArray=[],sourceID=0):
    print "sourceID " + str(sourceID)
    DBcursor = self.BooksDB.cursor()                             # obtention d'un curseur
    
    for bookInfos in booksArray :

        #Ajout des auteurs dans la base de donnée
        authors = bookInfos[7]
        authorsID = ""
            
        DBcursor.execute("SELECT * FROM books WHERE isbn =(?)" , [bookInfos[0]])

        if DBcursor.fetchall() == [] :
            print "Le livre %s n'existe pas, il va etre ajoute" % (bookInfos[1].encode("utf8"))

            for author in authors :
                author[1] = string.capitalize(author[1].lower())
                author[0] = author[0].upper()
                #Vérifie que l'auteur n'est pas dans la base
                print type(author[0])
                print type(author[1])
                DBcursor.execute("SELECT * FROM authors WHERE name =(?) AND forname =(?)" , (author[0], author[1]))
                queryReturn = DBcursor.fetchall()

                if queryReturn == [] :
                    print "L'auteur %s %s n'existe pas, il va etre ajoute" % (author[0].encode("utf8"), author[1].encode("utf8"))
                    DBcursor.execute("INSERT INTO authors VALUES  (NULL, ?, ?)", (author[0], author[1]))
                    authorsID = int(DBcursor.lastrowid)
            
                #Ajout de l'auteur
                else :
                    authorsID = queryReturn[0][0]

            genres = bookInfos[8]
            for genre in genres :
                genre = string.capitalize(genre.lower())
                #Vérifie que le genre n'est pas dans la base
                DBcursor.execute("SELECT * FROM genres WHERE genre =(?)" , [genre])
                queryReturn = DBcursor.fetchall()

                if queryReturn == [] :
                    print "Le genre %s n'existe pas, il va etre ajoute" % (genre)
                    DBcursor.execute("INSERT INTO genres VALUES  (NULL, ?)", [genre])
                    genresID = int(DBcursor.lastrowid)
            
                #Ajout de l'auteur
                else :
                    genresID = queryReturn[0][0]

            #print bookInfos[2]
            print bookInfos[2].encode("utf8")
            DBcursor.execute("INSERT INTO authorsbooks VALUES  (?, ?)", (bookInfos[0], authorsID))
            DBcursor.execute("INSERT INTO genresbooks VALUES  (?, ?)", (genresID , bookInfos[0]))
            print bookInfos[9]
            DBcursor.execute("INSERT INTO books VALUES  (?, ?, ?, ?, ?, ?, ? , ? , ? , ?)", (bookInfos[0], bookInfos[1], bookInfos[2], bookInfos[3], bookInfos[4], bookInfos[5], bookInfos[6], sourceID, bookInfos[10], bookInfos[11]))


    self.BooksDB.commit()

    DBcursor.close()
开发者ID:Quihico,项目名称:passion-xbmc,代码行数:60,代码来源:DBlib.py


示例4: convertToPCM

    def convertToPCM(self, jniname, pcmname, indirectIn = 0, indirectOut = 0, unbox = 0):
        indo = ''
        if indirectOut:
            indo = '*'

        if indirectIn:
            unbox = "jclass boxclazz = env->FindClass(\"java/lang/" +\
                    self.wrapper_class + "\");\n" +\
                    "jmethodID unboxmethod = env->GetMethodID(boxclazz, \"" +\
                    self.java_type + "Value\", \"()" + self.java_sig + "\");\n" +\
                    indo + pcmname + ' = static_cast<' + self.pcm_type + ">(" +\
                    'env->Call' + string.capitalize(self.java_type) +\
                    "Method(tmpobj, unboxmethod));\n"
            return self.readJNIReference(unbox, jniname)

        if unbox:
            return "{\n" +\
                   "jclass boxclazz = env->FindClass(\"java/lang/" +\
                   self.wrapper_class + "\");\n" +\
                   "jmethodID unboxmethod = env->GetMethodID(boxclazz, \"" +\
                    self.java_type + "Value\", \"()" + self.java_sig + "\");\n" +\
                    indo + pcmname + ' = static_cast<' + self.pcm_type + ">(" +\
                    'env->Call' + string.capitalize(self.java_type) +\
                    "Method(" + jniname + ", unboxmethod));\n}\n"
        
        return indo + pcmname + ' = static_cast<' + self.pcm_type + '>(' + jniname + ');'
开发者ID:OpenCMISS-Dependencies,项目名称:libcellml,代码行数:26,代码来源:jnutils.py


示例5: findDescriptions

def findDescriptions(def_file,def_delimiter,sbtype):
    '''
    Preprocesses the definition file in order to enable some nice mouseover effects for the known column names.

    Parameters
    ----------
    def_file : str
       SBtab definition file as string representation.
    def_delimiter : str
       Delimiter used for the columns; usually comma, tab, or semicolon.
    sbtype : str
       SBtab attribute TableType.
    '''    
    col2description = {}
    col_dsc         = False

    columnrow = def_file.split('\n')[1]
    columnrowspl = columnrow.split(def_delimiter)

    for row in def_file.split('\n'):
        splitrow = row.split(def_delimiter)
        if len(splitrow) != len(columnrowspl): continue
        if row.startswith('!!'): continue
        if row.startswith('!'):
            for i,elem in enumerate(splitrow):
                if elem == "!Description":
                    col_dsc = i
        if not string.capitalize(splitrow[2]) == string.capitalize(sbtype): continue
        if col_dsc and not splitrow[2].startswith('!'): col2description[splitrow[0]] = splitrow[col_dsc]

    return col2description
开发者ID:derHahn,项目名称:SBtab,代码行数:31,代码来源:sbtab2html.py


示例6: render_controller

def render_controller(name, noforce):
    # 
    print " creating controller: " 
    print " -- ", name 
    
    # add the auto generated warning to the outputfile
    infile = open (os.path.normpath(PARTS_DIR + "autogenerated_warning.txt"), "r")
    ostr = infile.read()
    infile.close()
    
    # add a creation date
    ostr = ostr + os.linesep
    ostr = ostr + "# date created: \t" + str(datetime.date.today())
    ostr = ostr + os.linesep
    
    # Add the model_stub part1 content to the newly generated file. 
    infile = open (os.path.normpath( PARTS_DIR + "controller_stub_part0.py"), "r")
    ostr = ostr + infile.read()
    infile.close()
    
    #pluralname = powlib.plural(model)
    #ostr += powlib.tab +  powlib.tab + "table_name=\"" + pluralname + "\""
    ostr += powlib.linesep
    ostr += "import " + string.capitalize( name ) 
    ostr += powlib.linesep
    ostr += powlib.linesep
    
    classname = string.capitalize( name ) + "Controller"
    ostr += "class " + classname + "(BaseController.BaseController):"
    
    # Add the controller_stub part 1 content to the newly generated file. 
    infile = open (os.path.normpath(PARTS_DIR + "controller_stub_part1.py"), "r")
    ostr = ostr + infile.read()
    ostr+= powlib.tab + powlib.tab + "self.modelname = \"" + string.capitalize( name ) + "\"" + powlib.linesep
    
    # Add the controller_stub part2 content to the newly generated file. 
    infile = open (os.path.normpath(PARTS_DIR + "controller_stub_part2.py"), "r")
    ostr = ostr + infile.read()
    infile.close()
    
    filename = os.path.normpath ( "./controllers/" + classname +".py" )
    
    if os.path.isfile( os.path.normpath(filename) ) and noforce:
        print " --", filename + " already exists... (Not overwrtitten. Use -f to force ovewride)"
    else:
        ofile = open(  filename , "w+") 
        print  " -- created controller " + filename
        ofile.write( ostr )
        ofile.close()
    #
    # check if BaseModel exist and repair if necessary
    if os.path.isfile(os.path.normpath( "./controllers/BaseController.py")):
        #BaseModel exists, ok.
        pass
    else:
        # copy the BaseClass
        powlib.check_copy_file(os.path.normpath( "./stubs/controllers/BaseController.py"), os.path.normpath( "./controllers/"))
    
    render_test_stub( name, classname )
    return
开发者ID:connimark,项目名称:yourhands,代码行数:60,代码来源:generate_controller.py


示例7: expandcasedict

	def expandcasedict(self):
		for i in lowercase_ligatures:
			casedict[i] = i.upper()
		for i in lowercase:
			if i not in casedict.keys():
				if string.capitalize(i) in uppercase:
					casedict[i] = string.capitalize(i)
开发者ID:SayCV,项目名称:tools-FDK,代码行数:7,代码来源:gString.py


示例8: writeSection

def writeSection(index, nav, destPath, section):
    out = writer(open(destPath + 'x.%s.html' % section.secNo, 'w'))
    out('<HTML><HEAD><TITLE>%s: %s -- %s</TITLE></HEAD>\n' % (
        string.capitalize(section.tag), section.secNo,
        stripMarkup(section.title)))
    out('<BODY BGCOLOR=WHITE FGCOLOR=BLACK>')
    out(nav.render(1))
    out('<HR>')
    out('<H2>%s: %s -- %s</H2>' % (
        string.capitalize(section.tag), section.secNo, render(section.title)))

    writeSectionTOC(out, section)

    out(renderBody(section, index))
        
    out('<HR>')
    out(nav.render(0))
    out('</BODY></HTML>')

    for s in section.sections:
        p, pt, n, nt = getNextPrev(s.secNo, index)
        nnav = nav.newPlusAlter(up = 'x.%s.html' % section.secNo,
                                upText = stripMarkup(section.title),
                                next = n, nextText = nt,
                                back = p, backText = pt)
                                
        writeSection(index, nnav, destPath, s)
开发者ID:BackupTheBerlios,项目名称:skunkweb-svn,代码行数:27,代码来源:htmlSkunkDoc.py


示例9: addAction

def addAction(portal_type, portal_type_type, country, amortisation_method):
    print 'Adding UI tab "Amortisation Details" for method %s on portal_type %s... ' % (
        amortisation_method,
        portal_type,
    ),
    id = "%s_%s_amortisation_details_view" % (country, amortisation_method)
    if id in [x.id for x in portal_type.listActions()]:
        print "Already exists"
    else:
        if portal_type_type == "Immobilisation":
            action = "%s_Immobilisation_viewDetails" % amortisation_method
        else:
            action = "%s_Item_viewAmortisationDetails" % amortisation_method
        portal_type.addAction(
            id=id,
            name="Amortisation Details",
            action=action,
            condition="object/IsUsing%s%sAmortisationMethod"
            % (capitalize(country), "".join([capitalize(x) for x in amortisation_method.split("_")])),
            permission=("View",),
            category="object_view",
            visible=1,
        )
        print "OK"
    return printed
开发者ID:Nexedi,项目名称:erp5,代码行数:25,代码来源:AmortisationSystem_addAmortisationMethod.py


示例10: routeFrostbitePacket

 def routeFrostbitePacket(self, packet):
     if packet is None:
         self.warning('cannot route empty packet : %s' % traceback.extract_tb(sys.exc_info()[2]))
     
     eventType = packet[0]
     eventData = packet[1:]
     
     match = re.search(r"^(?P<actor>[^.]+)\.on(?P<event>.+)$", eventType)
     if match:
         func = 'On%s%s' % (string.capitalize(match.group('actor')), \
                            string.capitalize(match.group('event')))
         #self.debug("-==== FUNC!!: " + func)
         
     if match and hasattr(self, func):
         #self.debug('routing ----> %s' % func)
         func = getattr(self, func)
         event = func(eventType, eventData)
         #self.debug('event : %s' % event)
         if event:
             self.queueEvent(event)
         
     elif eventType in self._eventMap:
         self.queueEvent(b3.events.Event(
                 self._eventMap[eventType],
                 eventData))
     else:
         if func:
             data = func + ' '
         data += str(eventType) + ': ' + str(eventData)
         self.debug('TODO: %r' % packet)
         self.queueEvent(b3.events.Event(b3.events.EVT_UNKNOWN, data))
开发者ID:Classixz,项目名称:b3bot-codwar,代码行数:31,代码来源:abstractParser.py


示例11: __init__

    def __init__(self, chord):
        #
        # Chord("abm7sus4/g#") =>
        #
        #  [Ab][m7sus4]/[G#]
        #
        #  root = Ab
        #  triad = m7sus4
        #  bass  = G#
        #
        #  minor = True
        #
        self.root = None
        self.triad = None
        self.bass = None
        self.bassrest = None
        self.minor = None

        c = re.match("^([(])?([A-Ga-g][b#]?)([^/]*)[/]?([A-Ga-g][b#]?)?(.*)$", chord)
        if not c:
            raise ChordError("Unable to parse '%s' as a valid chord" % chord)
        self.opening_brace = c.group(1)
        self.root = string.capitalize(c.group(2))
        if c.group(3):
            self.triad = c.group(3)
        if c.group(4):
            self.bass = string.capitalize(c.group(4))
        if c.group(5):
            self.bassrest = c.group(5)

        if self.triad:
            t = re.sub("maj", "", self.triad)
            if t.startswith("m"):
                self.minor = True
开发者ID:jperkin,项目名称:py-chordpro,代码行数:34,代码来源:pychord.py


示例12: setSound

    def setSound(self, value, secs=0.5, octave=4, hamming=True, log=True):
        """Set the sound to be played.

        Often this is not needed by the user - it is called implicitly during
        initialisation.

        :parameters:

            value: can be a number, string or an array:
                * If it's a number between 37 and 32767 then a tone will be generated at that frequency in Hz.
                * It could be a string for a note ('A','Bfl','B','C','Csh'...). Then you may want to specify which octave as well
                * Or a string could represent a filename in the current location, or mediaLocation, or a full path combo
                * Or by giving an Nx2 numpy array of floats (-1:1) you can specify the sound yourself as a waveform

            secs: duration (only relevant if the value is a note name or a frequency value)

            octave: is only relevant if the value is a note name.
                Middle octave of a piano is 4. Most computers won't
                output sounds in the bottom octave (1) and the top
                octave (8) is generally painful
        """
        self._snd = None  # Re-init sound to ensure bad values will raise RuntimeError during setting

        try:#could be '440' meaning 440
            value = float(value)
            #we've been asked for a particular Hz
        except (ValueError, TypeError):
            pass  #this is a string that can't be a number
        else:
            self._fromFreq(value, secs, hamming=hamming)

        if isinstance(value, basestring):
            if capitalize(value) in knownNoteNames:
                if not self._fromNoteName(capitalize(value), secs, octave, hamming=hamming):
                    self._snd = None
            else:
                #try finding the file
                self.fileName=None
                for filePath in ['', mediaLocation]:
                    p = path.join(filePath, value)
                    if path.isfile(p):
                        self.fileName = p
                    elif path.isfile(p + '.wav'):
                        self.fileName = p + '.wav'
                if self.fileName is None:
                    raise IOError, "setSound: could not find a sound file named " + value
                elif not self._fromFile(value):
                    self._snd = None
        elif type(value) in [list,numpy.ndarray]:
            #create a sound from the input array/list
            if not self._fromArray(value):
                self._snd = None

        #did we succeed?
        if self._snd is None:
            raise RuntimeError, "Could not make a "+value+" sound"
        else:
            if log and self.autoLog:
                logging.exp("Set %s sound=%s" %(self.name, value), obj=self)
            self.status=NOT_STARTED
开发者ID:BrainTech,项目名称:psychopy,代码行数:60,代码来源:sound.py


示例13: decrypt

def decrypt(): 
	# initializing the message variable (the final plaintext output) 
	message = "" 

	# making sure the key is numeric, if not, asking the user for the key again 
	while True: 
		try: 
			key = input("Please enter the secret key: ") 
			break 
		except: 
			print "Enter a ******* number, idiot!" 

	# asking for the encrypted text 
	code = raw_input("Enter the encrypted text: ") 

	# splitting it into chunks 
	numberslist = code.split(" ") 

	for number in numberslist:								# going element by element in the list... 
		if number == "": 
			message += " "									# replacing two spaces with one space 
		else: 
			try:											# checking if the element is numeric 
				index = (int(number) - (key**2) + key - 1)	# elemenating all prior mathematical operations... 
				try: 
					letter = string.lowercase[index]		# checking if the key is within range for the encrypted text 
					message += letter						# concatenating the letter (or punctuation mark) to the final message in the process 
				except: 
					print "You have got the wrong key." 
					break 
			except ValueError: 
				letter = number 
				message += letter 
			 
	print string.capitalize(message)						# capitalizing the first letter. Might as well make it look good... 
开发者ID:ryleyherrington,项目名称:crypto,代码行数:35,代码来源:cypher.py


示例14: add_ldap_user

def add_ldap_user(username,password):
	if not username:
		print "please input username"
	else:
		ldapconn = ldap.open(LDAP_HOST)
		ldapconn.simple_bind(MGR_USER,MGR_PASSWD)

		firstname = username.split('.')[0]
		lastname = username.split('.')[1]

		firstname = string.capitalize(firstname)	
		lastname = string.capitalize(lastname)

		attrs = {}	
		dn = "uid=%s,%s" %(username,LDAP_BASE_DN)
		attrs['objectclass'] = ['top','person','organizationalPerson','inetorgperson']
		attrs['cn'] = firstname + " " + lastname
		attrs['sn'] = firstname
		attrs['givenName'] = lastname
		attrs['mail'] = username + "@cn.nytimes.com"
		attrs['uid'] = username
		attrs['userPassword'] = password
		ldif = ldap.modlist.addModlist(attrs)
		ldapconn.add_s(dn,ldif)
		ldapconn.close
开发者ID:yimeng,项目名称:nytimes,代码行数:25,代码来源:user.py


示例15: gen_protobuf_impl

def gen_protobuf_impl(module, folder, settings):
    base_folder = os.path.join(settings['_root_'], '_Project_-Protobuf/src/main/')
    base_folder = format_line(base_folder, settings)
    base_folder = base_folder.replace('\\', '/')
    #mapper
    folder0 = os.path.join(folder, 'protobuf', module['name'])
    print folder0
    os.makedirs(folder0)
    outname = string.capitalize(module['name']) + 'Proto.proto'
    proto_file = os.path.join(base_folder, outname)
    kwargs = {}
    kwargs.update(settings)
    kwargs['now'] = datetime.now()
    kwargs['_module_'] = module['name']
    kwargs['_moduleC_'] = string.capitalize(module['name'])
    #entity and service
    _tbis = []
    for tbl in module['tables']:
        tbi = dbm.get_table(module, tbl)
        _tbis.append(tbi)
    kwargs['_tbis'] = _tbis
    #java out
    java_out = os.path.join(settings['_root_'], '_Project_-Protobuf/src/main/java')
    java_out = format_line(java_out, settings)
    cmd = 'protoc --proto_path=%s --java_out=%s %s' % (base_folder, java_out, proto_file)
    print cmd
    os.system(cmd)
    #render java wrapper
    for tbl in _tbis:
        kwargs['_tbi'] = tbl
        fnamet = os.path.join(folder0, 'P%sWrapper.java' % tbl.entityName)
        javagen.render_protobuf_wrapper(fnamet, **kwargs)
    #ios out
    cpp_out = os.path.join(settings['_root_'], '_Project_-Protobuf/src/main/ios/Models', module['name'])
    cpp_out = format_line(cpp_out, settings)
    os.makedirs(cpp_out)
    cmd = 'protoc --proto_path=%s --cpp_out=%s %s' % (base_folder, cpp_out, proto_file)
    print cmd
    os.system(cmd)
    #rename cpp to .hh and .mm for iOS
    fname = os.path.join(cpp_out, outname.replace('.proto', ''))
    print fname
    os.rename(fname + '.pb.h', fname + '.pb.hh')
    os.rename(fname + '.pb.cc', fname + '.pb.mm')
    with open(fname + '.pb.mm', 'r') as f:
        txt = f.read()
        txt = txt.replace('Proto.pb.h', 'Proto.pb.hh')
        with open(fname + '.pb.mm', 'w+') as fw:
            fw.write(txt)
    with open(fname + '.pb.hh', 'r') as f:
        txt = f.read()
        txt = txt.replace('Proto.pb.h', 'Proto.pb.hh')
        with open(fname + '.pb.hh', 'w+') as fw:
            fw.write(txt)
    #generate ios
    for tbl in _tbis:
        kwargs['_tbi'] = tbl
        fname = os.path.join(cpp_out, 'TS' + tbl.entityName)
        javagen.render_ios(fname, **kwargs)
开发者ID:343829084,项目名称:argo,代码行数:59,代码来源:project-gen.py


示例16: convert_to_pinyin

def convert_to_pinyin(name):
    name = tradition2simple(name)
    py = Pinyin()
    pinyin = ' '.join(
            [string.capitalize(py.get_pinyin(name[1:], '')),
            string.capitalize(py.get_pinyin(name[0], ''))]
    )
    return pinyin
开发者ID:pandasasa,项目名称:name,代码行数:8,代码来源:process_country_gender_zh.py


示例17: index

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html

    if you need a simple wiki simply replace the two lines below with:
    return auth.wiki()
    """
    import string
    city_msg = ''
    if request.vars.city and request.vars.roles:
	city = string.capitalize(request.vars.city)
	roles = request.vars.roles.replace(' ', '').split(',') 
	city_msg = 'Showing results in ' + city
	listings= None
	for role in roles:
	    listing = db((db.listing.id == db.listing_role.listing_ndx) &
		(db.listing.city == city) &
		(db.listing_role.role_ndx == db.role.id) &
		(db.role.role_name == role)).select(
		    db.listing.id,
		    db.listing.created_by,
		    db.listing.title,
		    db.listing.city,
		    db.listing.date_created,
		    orderby=~db.listing.date_created)
	    if listing and listings:
		listings = listings |listing
	    elif listing:
		listings=listing
    elif request.vars.city and not request.vars.roles:
	city = string.capitalize(request.vars.city)
	city_msg = 'Showing results in ' + city
	listings = db(db.listing.city == city).select(orderby=~db.listing.date_created)
    elif request.vars.roles:
	roles = request.vars.roles.replace(' ', '').split(',') 
	listings= None
	for role in roles:
	    listing = db((db.listing.id == db.listing_role.listing_ndx) &
		(db.listing_role.role_ndx == db.role.id) &
		(db.role.role_name == role)).select(
		    db.listing.id,
		    db.listing.created_by,
		    db.listing.title,
		    db.listing.city,
		    db.listing.date_created,
		    orderby=~db.listing.date_created)
	    if listing and listings:
		listings = listings |listing
	    elif listing:
		listings = listing
	city_msg = 'Showing results in all cities'
    elif not request.vars.roles and not request.vars.city:
        listings=db(db.listing).select(orderby=~db.listing.date_created)
	city_msg = 'Showing listings in all cities'
    return dict(listings=listings,user=auth.user,city_msg=city_msg)
开发者ID:mattwylder,项目名称:bandmates,代码行数:56,代码来源:default.py


示例18: renderBody

def renderBody(x, index):
    s = []
    for i in x.contents:
        if type(i) == types.StringType:
            s.append(i)
        elif i.tag == 'label':
            s.append('<A NAME="%s"></A>' % i.args['id'])
        elif i.tag == 'xref':
            refSec = i.args['id']
            try:
                sec = index['howto']['xref'][refSec]
            except KeyError:
                if globals.VERBOSE:
                    print 'invalid section reference %s' % refSec
                    #print 'keys=', index['howto']['xref'].keys()
                globals.ERRORS.append('invalid section reference %s' % refSec)
                s.append(renderBody(i, index))
            else:
                if type(sec) == type(()):
                    target = '#' + sec[1]
                    sec = sec[0]
                else:
                    target = ''
                s.append('<A HREF="x.%s.html%s">' % (sec.secNo, target))
                s.append(renderBody(i, index))
                if i.args.has_key('noparen'):
                    s.append(' %s: %s - %s</A>' % (
                        string.capitalize(sec.tag), sec.secNo,
                        stripMarkup(sec.title)))
                else:
                    s.append(' (%s: %s - %s)</A>' % (
                        string.capitalize(sec.tag), sec.secNo,
                        stripMarkup(sec.title)))
                
        else:
            if htmlMap.get(i.tag) is None:
                if globals.VERBOSE:
                    print 'skipping %s tag' % i.tag
                globals.ERRORS.append('skipping %s tag' % i.tag)
                continue
            tagmap = htmlMap[i.tag]
            if type(tagmap) == types.TupleType:
                outTag = tagmap[0]
                tagmap = tagmap[1]
            else:
                outTag = i.tag
            args = string.join(map(lambda x:'%s="%s"'%x, i.args.items()), ' ')
            if args:
                args = ' ' + args
            if not tagmap:
                args = args+'/'
            s.append('<%s%s>' % (outTag, args))
            s.append(renderBody(i, index))
            if tagmap == 1:
                s.append('</%s>' % outTag)
    return string.replace(string.join(s, ''), '\n\n', '\n<p>')
开发者ID:BackupTheBerlios,项目名称:skunkweb-svn,代码行数:56,代码来源:htmlSkunkDoc.py


示例19: _viewData

 def _viewData(self, category):
     variable_names = self.categories[category][:]
     if category == 'configuration':
         self._missing()
     elif category == 'energy':
         EnergyViewer(self, string.capitalize(category),
                      self.time, self.inspector, variable_names)
     else:
         PlotViewer(self, string.capitalize(category),
                    self.time, self.inspector, variable_names)
开发者ID:acousticpants,项目名称:mmtk,代码行数:10,代码来源:TrajectoryViewer.py


示例20: AddClip

 def AddClip(self, path, name):
       self.buttons.append(wx.Button(self, label=string.capitalize(name[:-4])))
       self.buttons[-1].Bind(wx.EVT_BUTTON, self.OnClick)
       self.buttons[-1].myname = os.path.join(path, name)
       self.buttons[-1].SetToolTipString(string.capitalize(name[:-4]))
       self.sizer.Add(self.buttons[-1], 0, wx.ALIGN_CENTER|wx.ALL, 5)
       
       # Buttons won't align right with this next line. Why? 
       #self.buttons[-1].SetMaxSize(wx.Size(100, 50))
       self.Fit()
开发者ID:johnny2k,项目名称:Ryouba-Sound-Board,代码行数:10,代码来源:rsb.py



注:本文中的string.capitalize函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python string.capwords函数代码示例发布时间:2022-05-27
下一篇:
Python string.atoi函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap