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
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)
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
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)
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
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
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
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...
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
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()
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 + ');'
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))
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)
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
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)
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
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>')
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)
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()
def save_person(self): user = self.save_user() #create and save Person person = Person(user = user, email_primary = user.email, username = user.username, first_name=capitalize(self.cleaned_data["first_name"]), last_name = capitalize(self.cleaned_data["last_name"]), gender = self.cleaned_data["gender"]) person.save()
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)
def liste(database, doc, form, param): (z) = recupere_champs(database, form) # where = " WHERE zone = %s" % (z) # liste des acces faisant partie de la zone qassoc = "SELECT " + param + " FROM " + param + ", zone_"+ param + where + " AND " + param + ".id" + param + " = zone_" + param + ".id" + param # # liste des figures n'en faisant pas partie # on pourrait aussi toutes les selectionner et faire le test par programme. qautres = "SELECT " + param + " FROM " + param + " WHERE " + param + " NOT IN (" + qassoc # # on recupere les deux listes presents = database.query(qassoc + ";").dictresult() absents = database.query(qautres + ");").dictresult() doc.form(method = "POST", action = doc.script_name()) doc.push() doc.tr() doc.td(colspan=3, align="center", valign="center") doc.table( bgcolor = begoconf.basform_bgcolorleft) doc.push() doc.td() doc.pop() dico = afficheclefs.form_to_enreg(form) afficheclefs.display_zone(doc, dico, alignement="center") doc.pop() doc.push() doc.tr() doc.td(valign = "middle", align="center", colspan=3) doc.hidden(name="param", value=param) doc.submit(name = "action", value = "Fin Modif") doc.pop() doc.push() doc.tr() doc.push() doc.td(align="center", valign="center") doc.insert_text("Liste " + string.capitalize(param) + " hors de la zone") doc.br() zp = "zone_" + param + "_absents" liste_multiple(doc, zp, absents, param) doc.pop() doc.push() doc.td(align = "center", valign = "middle") doc.submit(name = "action", value = "Ajouter -->") doc.br() doc.submit(name = "action", value = "<-- Enlever") doc.pop() doc.push() doc.td(align = "center", valign = "middle") doc.insert_text("Liste " + string.capitalize(param) + " dans la zone") doc.br() zp = "zone_" + param + "_presents" liste_multiple(doc, zp, presents, param) doc.pop() doc.pop()
def getTypeName(typeIndex, scoped=0): """ Return a fully specified type name for this type index Return the scoped name if asked for it """ nameComponents = [] name = '' if scoped: typeName = interrogate_type_scoped_name(typeIndex) else: typeName = interrogate_type_name(typeIndex) if typeIndex == 0: FFIConstants.notify.debug('typeIndex 0: ' + typeName) if interrogate_type_is_wrapped(typeIndex): typeName = getTypeName(interrogate_type_wrapped_type(typeIndex)) if interrogate_type_is_const(typeIndex): nameComponents.append('const') if interrogate_type_is_pointer(typeIndex): nameComponents.append('ptr') if interrogate_type_is_signed(typeIndex): # signed is now built into the type name #nameComponents.append('signed') pass if interrogate_type_is_unsigned(typeIndex): # unsigned is now built into the type name #nameComponents.append('unsigned') pass if interrogate_type_is_long(typeIndex): nameComponents.append('long') if interrogate_type_is_longlong(typeIndex): nameComponents.append('longLong') if interrogate_type_is_short(typeIndex): nameComponents.append('short') if (len(nameComponents) > 0): typeName = string.capitalize(typeName[0]) + typeName[1:] nameComponents.append(typeName) for i in range(len(nameComponents)): if (i == 0): name = name + nameComponents[i] else: name = name + string.capitalize(nameComponents[i][0]) + nameComponents[i][1:] FFIConstants.notify.debug('typeIndex: ' + `typeIndex` + ' typeName: ' + typeName + ' has name: ' + name) if not name: FFIConstants.notify.warning('typeIndex: ' + `typeIndex` + ' typeName: ' + typeName + ' has no name') name = "UnnamedType" return name
def __add__(self, other): """Add two lists of atoms.""" newdata = {} for key in self._data.keys(): accessfunc = "GetCartesian"+string.capitalize(key) try: otherdata = getattr(other, accessfunc)() except AttributeError: accessfunc = "Get"+string.capitalize(key) otherdata = getattr(other, accessfunc)() selfdata = self._data[key] newdata[key] = Numeric.concatenate((selfdata, otherdata)) return apply(self.__class__, (self.GetPeriodicBoundaries(),), newdata)
def save_vendor(self): #create and save User user = self.save_user() #create and save Vendor vendor = Vendor(user = user, email_primary = user.email, username = user.username, company_name = capitalize(self.cleaned_data["company_name"]), rep_first_name= capitalize(self.cleaned_data["rep_first_name"]), rep_last_name = capitalize(self.cleaned_data["rep_last_name"]), website_url = self.cleaned_data["website_url"], buy_url = self.cleaned_data["buy_url"]) vendor.save()
def cmdEmote(ch, cmd, args): """ Perform an emotion, printings the arguments after the players name. """ if args == '': ch.writeToSelf("What do you want to say?\r\n") return 1 ch.writeToSelf(string.capitalize(ch.getName())+" "+args+"\r\n") ch.writeToOthers(string.capitalize(ch.getName())+" "+args+"\r\n") return 1
def sentence(self, str, addPeriod=1): "Make a sentence out of the string, s" str = string.strip(str) if str == "": return str # Remove leading and trailing spaces if addPeriod: period = ". " else: period = "" if len(str) == 1: return string.capitalize(str[0]) + period return string.capitalize(str[0]) + str[1:len(str)] + period
def save(self, user): # save updated Person try: person = Person.objects.get(user=user) except ObjectDoesNotExist: return redirect('/') else: person.first_name = capitalize(self.cleaned_data["first_name"]) person.last_name = capitalize(self.cleaned_data["last_name"]) person.gender = self.cleaned_data["gender"] person.gift_freq = self.cleaned_data["gift_freq"] person.max_gift_price = self.cleaned_data["max_gift_price"] person.min_gift_price = self.cleaned_data["min_gift_price"] person.save()
def __str__(self): List = self.Dict.keys() ResultList = [] i = 0 while i != len(List): key = List[i] if type(key) == types.UnicodeType: name = key.encode(self.Encoding) else: name = key field = string.capitalize(name) + self.Sep + string.capitalize(self.Dict[key]) ResultList.append(field) i = i + 1 resultStr = string.join(ResultList, self.ListSep) return resultStr
def generateName() : female = bool(random.getrandbits(1)) myline = "" if female : lines = open(girl).read().splitlines() else : lines = open(male).read().splitlines() myline =random.choice(lines) lines = open(last).read().splitlines() return string.capitalize(myline) + " " + string.capitalize(random.choice(lines))
'atan', 'cos', 'cosh', 'exp', 'log', 'log10', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'real', 'imag', ] for i in lst: I = string.capitalize(i) print 'template<class TV,class Structure,class Storage,unsigned alignement,int nr>' print 'typename TypePromote<' + I + ',typename TV::template SubType<0>::T>::T ' + i + '(const MatElem<TV,Structure,Storage,alignement,nr> &me) {' print ' return ' + i + '((typename TV::template SubType<0>::T)me);' print '}' lst = [ ('Plus', '+'), ('Minus', '-'), ('Modulus', '%'), ('Multiplies', '*'), ('Divides', '/'), ('Equal', '=='), ('NotEqual', '!='), ('Less', '<'), ('Greater', '>'),
def _get_clear(self): return string.capitalize(self.getAttribute("CLEAR"))
def titlecase(s): words = s.split() capwords = [string.capitalize(w) for w in words] return " ".join(capwords)
def deselect(self, el): e = string.capitalize(el) self.c[e]['relief'] = FLAT self.c[e]['bg'] = self.color(e, sel=0)
def add_unredirected_header(self, key, val): """Add a header that will not be added to a redirected request.""" self.unredirected_hdrs[string.capitalize(key)] = val
#!/usr/bin/env python # encoding:utf8 # import module from module.module import randStr import string # 导入包 import pack.testPack as test __author__ = 'flybird1971' timer = 1 while True: if timer > 10: break timer += 1 print string.capitalize(randStr(timer)) print "*" * 32 test.show()
def deploy_img(img_path, vol_size, arch, region, src_ami, dev=None, kernel_id=None, ramdisk_id=None, platform=None, remove_old=False, **cluster_kwargs): """ Deploy a filesystem image as a new AMI in a given region. This method creates a 1-node host cluster in the desired `region`, copies the filesystem image to the cluster, creates and attaches a new EBS volume with size `vol_size`, installs the image onto the new EBS volume, creates a snapshot of the resulting volume and registers a new AMI in the `region`. """ cfg = config.StarClusterConfig().load() ec2 = cfg.get_easy_ec2() ec2.connect_to_region(region) src_img = ec2.get_image(src_ami) kernel_id = kernel_id or src_img.kernel_id ramdisk_id = ramdisk_id or src_img.ramdisk_id itypemap = dict(i386='m1.small', x86_64='m1.large') dev = dev or dict(i386='/dev/sdj', x86_64='/dev/sdz')[arch] cm = cluster.ClusterManager(cfg, ec2) try: log.info("Checking for existing imghost cluster") cl = cm.get_cluster('imghost') log.info("Using existing imghost cluster") except exception.ClusterDoesNotExist: log.info("No imghost cluster found, creating...") default = cm.get_default_cluster_template() cl = cm.get_cluster_template(default, 'imghost') keys = ec2.get_keypairs() key = None for k in keys: if cfg.keys.has_key(k.name): key = cfg.keys.get(k.name) key['keyname'] = k.name break if key: cluster_kwargs.update(key) hostitype = itypemap[src_img.architecture] cluster_kwargs.update( dict(cluster_size=1, cluster_shell="bash", node_image_id=src_ami, node_instance_type=hostitype)) cl.update(cluster_kwargs) cl.start(create_only=True, validate=True) cl.wait_for_cluster() host = cl.master_node log.info("Copying %s to /mnt on master..." % img_path) host.ssh.put(img_path, '/mnt/') bname = os.path.basename(img_path) if bname.endswith('.tar.gz'): log.info("Extracting image(s)...") host.ssh.execute('cd /mnt && tar xvzf %s' % bname) bname = bname.replace('.tar.gz', '') if not host.ssh.isfile('/mnt/%s' % bname): raise exception.BaseException("/mnt/%s does not exist" % bname) log.info("Creating EBS volume") vol = ec2.create_volume(vol_size, host.placement) log.info("Attaching EBS volume %s to master as %s" % (vol.id, dev)) vol.attach(host.id, dev) log.info("Waiting for drive to attach...") s = spinner.Spinner() s.start() realdev = '/dev/xvd%s' % dev[-1] while not host.ssh.path_exists(realdev): time.sleep(10) s.stop() log.info("Installing image on volume %s ..." % vol.id) host.ssh.execute("cat /mnt/%s > %s" % (bname, realdev)) log.info("Checking filesystem...") host.ssh.execute("e2fsck -pf %s" % realdev) log.info("Resizing filesystem to fit EBS volume...") host.ssh.execute("resize2fs %s" % realdev) vol.detach() while vol.update() != 'available': time.sleep(10) xarch = arch if xarch == 'i386': xarch = 'x86' snapdesc = 'StarCluster %s %s EBS AMI Snapshot' % (platform, xarch) snap = ec2.create_snapshot(vol, description=snapdesc, wait_for_snapshot=True) vol.delete() bmap = ec2.create_root_block_device_map(snap.id, add_ephemeral_drives=True) imgname = string.lower(platform.replace(' ', '-')) imgname = 'starcluster-base-%s-%s' % (imgname, xarch) imgdesc = 'StarCluster Base %s %s (%s)' % (platform, xarch, string.capitalize(region)) oldimg = ec2.get_images(filters=dict(name=imgname)) if oldimg: oldimg = oldimg[0] oldsnap = ec2.get_snapshot( oldimg.block_device_mapping['/dev/sda1'].snapshot_id) if remove_old: log.info("Deregistering old AMI: %s" % oldimg.id) oldimg.deregister() log.info("Deleting old snapshot: %s" % oldsnap.id) oldsnap.delete() else: log.info("Existing image %s already has name '%s'" % (oldimg.id, imgname)) log.info("Please remove old image %s and snapshot %s" % (oldimg.id, oldsnap.id)) log.info("Then register new AMI with snapshot %s and name '%s'" % (snap.id, imgname)) return img = ec2.register_image(name=imgname, description=imgdesc, architecture=arch, kernel_id=kernel_id, ramdisk_id=ramdisk_id, root_device_name='/dev/sda1', block_device_map=bmap) return img
def vtkLoadPythonTkWidgets(interp): """vtkLoadPythonTkWidgets(interp) -- load vtk-tk widget extensions This is a mess of mixed python and tcl code that searches for the shared object file that contains the python-vtk-tk widgets. Both the python path and the tcl path are searched. """ X = vtkCommonCorePython.vtkVersion.GetVTKMajorVersion() Y = vtkCommonCorePython.vtkVersion.GetVTKMinorVersion() modname = 'vtkRenderingPythonTkWidgets' name = '%s-%d.%d' % (modname, X, Y) pkgname = string.capitalize(string.lower(modname)) # find out if the file is already loaded loaded = interp.call('info', 'loaded') if string.find(loaded, pkgname) >= 0: return # create the platform-dependent file name prefix = '' if sys.platform == 'cygwin': prefix = 'cyg' elif os.name == 'posix': prefix = 'lib' extension = interp.call('info', 'sharedlibextension') filename = prefix + name + extension # create an extensive list of paths to search pathlist = sys.path # add tcl paths, ensure that {} is handled properly try: auto_paths = string.split(interp.getvar('auto_path')) except AttributeError: auto_paths = interp.getvar('auto_path') for path in auto_paths: prev = str(pathlist[-1]) try: # try block needed when one uses Gordon McMillan's Python # Installer. if len(prev) > 0 and prev[0] == '{' and prev[-1] != '}': pathlist[-1] = prev + ' ' + path else: pathlist.append(path) except AttributeError: pass # a common place for these sorts of things if os.name == 'posix': pathlist.append('/usr/local/lib') # attempt to load for path in pathlist: try: # If the path object is not str, it means that it is a # Tkinter path object. if type(path) != str: path = path.string # try block needed when one uses Gordon McMillan's Python # Installer. if len(path) > 0 and path[0] == '{' and path[-1] == '}': path = path[1:-1] fullpath = os.path.join(path, filename) except AttributeError: pass if ' ' in fullpath: fullpath = '{' + fullpath + '}' if interp.eval('catch {load ' + fullpath + ' ' + pkgname + '}') == '0': return # re-generate the error interp.call('load', filename, pkgname)
def _get_atomlist_from_gms_outfile(assy, filename): """ Read the atoms from a GAMESS OUT file into an atom list, which is returned, unless there are no atoms in the file, in which case a warning is printed and None is returned. """ fi = open(filename, "rU") lines = fi.readlines() fi.close() dir, nodename = os.path.split(filename) mol = Chunk(assy, nodename) newAtomList = [] countdown = 0 equilibruim_found = False atoms_found = False for card in lines: if failpat.search( card): # GAMESS Aborted. No atom data will be found. print card env.history.message(redmsg(card)) break if noconvpat.search(card): # Geometry search is not converged. print card env.history.message(redmsg(card)) break # If this card is found: # "1 ***** EQUILIBRIUM GEOMETRY LOCATED *****\n" # we know we have a successfully optimized structure/set of atoms. # If this card is not found, the optimization failed for some reason. # Atom positions begin soon after this card. if card == "1 ***** EQUILIBRIUM GEOMETRY LOCATED *****\n": equilibruim_found = True continue # The atom positions we want ALWAYS begin 2 lines after this card: # " COORDINATES OF ALL ATOMS ARE (ANGS)\n" # which follows the previous card. # This is one way to fix the problem mentioned above. # I've commented the code below out since it needs further work to do what # we need, and there is a chance we will not need this if GAMESS-US has # the same number of lines (6) after the "EQUILIBRIUM" card above. # # P.S. The reason we do not just look for this card by itself is that there # can be many of them. There is only one "EQUILIBRIUM" card, and the # good atoms follow that card. # 050624 Mark if equilibruim_found: if card == " COORDINATES OF ALL ATOMS ARE (ANGS)\n": atoms_found = True reading_atoms = True countdown = 2 continue if not equilibruim_found or not atoms_found: continue if countdown: countdown -= 1 # print countdown, card # for debugging only. continue # The current card contains atom type and position. n = 0 if reading_atoms: # print "_get_atomlist_from_gms_outfile:", card if len(card) < 10: reading_atoms = False # Finished reading atoms. break m = irecpat.match(card) sym = capitalize(m.group(1)) try: PeriodicTable.getElement(sym) except: env.history.message( redmsg( "Warning: GAMESS OUT file: unknown element %s in: %s" % (sym, card))) else: xyz = map(float, (m.group(2), m.group(3), m.group(4))) a = Atom(sym, A(xyz), mol) newAtomList += [a] # Let caller handle history msgs. Mark 050712 # if not newAtomList: # msg = "Warning: GAMESS file contains no equilibrium geometry. No atoms read into part." # env.history.message( redmsg(msg)) # return None return newAtomList
# string format examples # access arguments by position print '{0}, {1}, {2}'.format('a', 'b', 'c') print '{}, {}, {}'.format('a', 'b', 'c') print '{2}, {1}, {0}'.format('a', 'b', 'c') print '{2}, {1}, {0}'.format(*'abc') print '{0}{1}{0}'.format('abra', 'cad') # access arguments by name print 'Names: {james}, {roger}'.format(james='hello', roger='world') print 'repr() shows quotes: {!r}; str() doesn\'t: {!s}'.format( 'test1', 'test2') # return a copy of word with only its first character capitalized print string.capitalize('word') print string.find('string to search from', 'from') # return -1 if sub string is not found print string.find('string to search from', 'from', 3, 6) # start from index 3, end at index 6 # like .find() but find the highest index print string.rfind('hello world hello', 'hello') # like find but raise ValueError exception when substring is not found print string.index('testing', 'test') print string.count('hello world hello world hello world', 'hello') print string.lower("LOWERCASE")
def create_invoice(self, sid): """generates a couchdb document and returns its document id """ db = MySQLdb.connect(**settings.DB_ARGS) c = db.cursor() #get leads_id c.execute( """SELECT leads_id from subcontractors_invoice_setup WHERE id = %s """, sid) result = c.fetchone() if result == None: self.__send_email_alert__( 'ALERT Not able to find leads_id from subcontractors_invoice_setup : %s for creating invoice.' % sid, 'Not able to find leads_id from subcontractors_invoice_setup : %s for creating invoice.' % sid) return leads_id = result[0] #get subcontractors_temp_ids c.execute( """SELECT subcontractors_id FROM subcontractors_invoice_setup_details WHERE subcontractors_invoice_setup_id = %s""", (sid, )) subcontractors_temp_ids = [] for x in c.fetchall(): subcontractors_temp_ids.append(str(x[0])) #get items c.execute("""SELECT st.client_price, st.currency, st.prepaid_start_date, st.job_designation, st.work_status, p.fname, p.lname FROM subcontractors_temp as st LEFT JOIN personal AS p ON st.userid = p.userid WHERE st.id IN (%s) AND st.leads_id = %s """ % (string.join(subcontractors_temp_ids, ','), leads_id)) items = c.fetchall() sub_total = 0 invoice_items = [] currency_check = [] #assume earliest date of 1 year earliest_starting_date = date.today() + timedelta(days=365) i = 1 for item in items: client_price, currency, start_date, job_designation, work_status, fname, lname = item if currency not in currency_check: currency_check.append(currency) if earliest_starting_date > start_date: earliest_starting_date = start_date end_date = self.add_week_days(start_date, WORKING_WEEKDAYS) if work_status == 'Part-Time': hours_per_day = 4 else: hours_per_day = 8 total_hours = WORKING_WEEKDAYS * hours_per_day staff_hourly_rate = client_price * 12 / 52 / 5 / hours_per_day staff_hourly_rate = round(staff_hourly_rate, 2) amount = round(total_hours * staff_hourly_rate, 2) invoice_item = dict( item_id=i, start_date=[start_date.year, start_date.month, start_date.day], end_date=[end_date.year, end_date.month, end_date.day], unit_price='%0.2f' % staff_hourly_rate, qty='%0.2f' % total_hours, amount='%0.2f' % amount, description='%s %s [%s]' % (string.capitalize(fname), string.capitalize(lname), job_designation), ) invoice_items.append(invoice_item) sub_total += amount i += 1 #check currency consistency if len(currency_check) > 1: self.__send_email_alert__( 'FAILED to create Trial Based First Month Invoice', 'Please check subcontractors_invoice_setup_id : %s\r\nMULTIPLE Currency for leads_id %s' % (sid, leads_id)) return #get apply_gst, fname, lname c.execute( """SELECT apply_gst, fname, lname, email, registered_domain from leads where id = %s """, (leads_id, )) apply_gst, client_fname, client_lname, client_email, registered_domain = c.fetchone( ) if apply_gst == 'yes': apply_gst = 'Y' else: apply_gst = 'N' #check currency and apply_gst consistency if apply_gst == 'Y' and currency != 'AUD': apply_gst = 'N' #update the leads table as well c.execute("""UPDATE leads set apply_gst='no' where id = %s""", (leads_id)) db.commit() self.__send_email_alert__( 'WARNING apply_gst and currency settings.', "leads_id %s has apply_gst = 'Y' and currency = %s\r\n overriding apply_gst to 'N' and setting leads.apply_gst to 'no'" % (leads_id, currency)) gst_amount = 0 sub_total = round(sub_total, 2) total_amount = sub_total if apply_gst == 'Y': gst_amount = round(sub_total * 0.1, 2) total_amount = round(total_amount + gst_amount, 2) #couchdb settings s = couchdb.Server(settings.CLIENT_DOCS_DSN) db_client_docs = s['client_docs'] #check if client has couchdb settings now = self.__get_phil_time__(as_array=True) r = db_client_docs.view('client/settings', startkey=[leads_id, now], endkey=[leads_id, [2011, 1, 1, 0, 0, 0, 0]], descending=True, limit=1) if len(r.rows) == 0: #no client settings, create one doc_settings = dict(added_by='MQ: First Months Invoice', apply_gst=apply_gst, client_id=leads_id, client_fname=client_fname, client_lname=client_lname, client_email=client_email, registered_domain=registered_domain, currency=currency, timestamp=now, type='client settings') db_client_docs.save(doc_settings) self.__send_email_alert__( 'Created client_settings document for leads_id : %s' % leads_id, pformat(doc_settings, indent=8)) #get last order id r = db_client_docs.view('client/last_order_id', startkey=[leads_id, "%s-999999999" % leads_id], endkey=[leads_id, ""], descending=True, limit=1) if len(r.rows) == 0: last_order_id = 1 else: last_order_id_str = r.rows[0].key[1] x, last_order_id = string.split(last_order_id_str, '-') last_order_id = int(last_order_id) last_order_id += 1 order_id = '%s-%08d' % (leads_id, last_order_id) doc_order = dict(added_by='MQ First Months Invoice', apply_gst=apply_gst, client_id=leads_id, history=[], type='order', added_on=now, items=invoice_items, status='new', order_id=order_id, sub_total='%0.2f' % sub_total, total_amount='%0.2f' % total_amount, gst_amount='%0.2f' % gst_amount, client_fname=client_fname, client_lname=client_lname, client_email=client_email, registered_domain=registered_domain, currency=currency, subcontractors_invoice_setup__id=int(sid), earliest_starting_date=[ earliest_starting_date.year, earliest_starting_date.month, earliest_starting_date.day ], pay_before_date=[ earliest_starting_date.year, earliest_starting_date.month, earliest_starting_date.day, 0, 0, 0 ]) #check if clients running balance can cover the order r = db_client_docs.view('client/running_balance', key=leads_id) if len(r.rows) == 0: running_balance = 0 else: running_balance = float(r.rows[0].value) TODO_COMMENT_OUT = """ if running_balance > total_amount: doc_order['status'] = 'paid' doc_order.pop('pay_before_date') doc_order['history'] = [ dict( timestamp = self.__get_phil_time__().strftime('%F %H:%M:%S'), changes = 'set status to paid since running balance can cover the amount', by = 'MQ First Month Invoice' ) ] """ doc_order['running_balance'] = '%0.2f' % running_balance #save order db_client_docs.save(doc_order) #return doc_id return doc_order['_id']
def __init__(self, context, url, title, infp, ctype): import tktools # self.infp = infp self.ctype = ctype self.context = context self.baseurl = context.get_baseurl() self.prefs = context.app.prefs self.settings = printing.settings.get_settings(context.app.prefs) if USER_DATA_DIR not in self.settings.user_data_dirs: self.settings.user_data_dirs.append(USER_DATA_DIR) settings = self.settings # self.title = title self.master = self.context.root self.root = tktools.make_toplevel(self.master, title="Print Dialog", class_="PrintDialog") # do this early in case we're debugging: self.root.protocol('WM_DELETE_WINDOW', self.cancel_command) self.root.bind("<Alt-w>", self.cancel_event) self.root.bind("<Alt-W>", self.cancel_event) self.cursor_widgets = [self.root] fr, top, botframe = tktools.make_double_frame(self.root) # Print to file controls: generalfr = tktools.make_group_frame( top, "general", "General options:", fill=X) self.cmd_entry, dummyframe = tktools.make_form_entry( generalfr, "Print command:") self.cmd_entry.insert(END, settings.printcmd) self.add_entry(self.cmd_entry) self.printtofile = IntVar(self.root) self.printtofile.set(settings.fileflag) fr = Frame(generalfr) fr.pack(fill=X) self.file_check = Checkbutton(fr, text = "Print to file:", command = self.check_command, variable = self.printtofile) self.file_check.pack(side=LEFT) self.file_entry = Entry(fr) self.file_entry.pack(side=RIGHT, fill=X) self.file_entry.insert(END, settings.printfile) self.add_entry(self.file_entry) if self.ctype != "application/postscript": # page orientation Frame(generalfr, height=2).pack() fr = Frame(generalfr) fr.pack(fill=X) self.orientation = StringVar(top) self.orientation.set(string.capitalize(settings.orientation)) opts = printing.paper.paper_rotations.keys() opts.sort() opts = tuple(map(string.capitalize, opts)) Label(fr, text="Orientation: ", width=13, anchor=E).pack(side=LEFT) Frame(fr, width=3).pack(side=LEFT) menu = apply(OptionMenu, (fr, self.orientation) + opts) width = reduce(max, map(len, opts), 6) menu.config(anchor=W, highlightthickness=0, width=width) menu.pack(expand=1, fill=NONE, anchor=W, side=LEFT) Frame(generalfr, height=2).pack() # font size fr = Frame(generalfr) fr.pack(fill=X) Label(fr, text="Font size: ", width=13, anchor=E).pack(side=LEFT) Frame(fr, width=3).pack(side=LEFT) e = self.fontsize = Entry(fr, width=12) e.insert(END, settings.get_fontspec()) e.pack(side=LEFT) self.add_entry(e) self.mod = self.get_type_extension() if self.mod.add_options: Frame(top, height=8).pack() self.mod.add_options(self, settings, top) # Command buttons: ok_button = Button(botframe, text="OK", command=self.ok_command) ok_button.pack(side=LEFT) cancel_button = Button(botframe, text="Cancel", command=self.cancel_command) cancel_button.pack(side=RIGHT) tktools.unify_button_widths(ok_button, cancel_button) tktools.set_transient(self.root, self.master) self.check_command()
from django.db import models from string import capitalize from django.contrib.auth.models import User from datetime import datetime CATEGORY_CHOICES = [ 'dating', 'school', 'work', 'friendship', 'family', 'other' ] labeled_choices = [(c, capitalize(c)) for c in CATEGORY_CHOICES] def get_username(model): if model.user: return model.user.username return model.nick class Post(models.Model): category = models.CharField(max_length=10, choices=labeled_choices) missed_opportunity = models.CharField(max_length=500) up_votes = models.IntegerField(default=0, editable=False) down_votes = models.IntegerField(default=0, editable=False) date_created = models.DateTimeField(default=datetime.now, editable=False) is_spam = models.BooleanField(editable=False) user = models.ForeignKey(User, editable=False, blank=True, null=True) nick = models.CharField(max_length=16, blank=True, null=True) def get_username(self):
try: language = getConfigExpress().GetString('language', 'english') checkLanguage = getConfigExpress().GetBool('check-language', 0) except: language = simbase.config.GetString('language', 'english') checkLanguage = simbase.config.GetBool('check-language', 0) def getLanguage(): return language print 'OTPLocalizer: Running in language: %s' % language if language == 'english': _languageModule = 'otp.otpbase.OTPLocalizer' + string.capitalize(language) else: checkLanguage = 1 _languageModule = 'otp.otpbase.OTPLocalizer_' + language print 'from ' + _languageModule + ' import *' exec 'from ' + _languageModule + ' import *' if checkLanguage: l = {} g = {} englishModule = __import__('otp.otpbase.OTPLocalizerEnglish', g, l) foreignModule = __import__(_languageModule, g, l) for (key, val) in englishModule.__dict__.items(): if not foreignModule.__dict__.has_key(key): print 'WARNING: Foreign module: %s missing key: %s' % ( _languageModule, key) locals()[key] = val
tname_list.append(tname) tbl = Table(tname, metadata, schema=schema, autoload=True) code = repr(tbl) code = code.replace('BoundMetaData()', 'metadata') code = code.replace('MSChar', 'CHAR') code = code.replace('MSSmallInteger(length=1)', 'Boolean()') code = code.replace('MSSmallInteger', 'SmallInteger') code = code.replace('MSDateTime', 'DateTime') code = code.replace('MSMediumText', 'TEXT') code = code.replace('MSDouble', 'Numeric') code = code.replace('MSMediumText', 'TEXT') code = code.replace('MSLongBlob', 'TEXT') code = code.replace('MSString', 'String') code = code.replace('MSDate', 'Date') code = code.replace('MSTime', 'DateTime') code = code.replace('MSInteger', 'Integer') code = code.replace('MSDecimal', 'Numeric') code = code.replace('MSEnum', 'Integer') caps = string.capitalize(tname) indexes = "\n".join([repr_index(index, tname) for index in tbl.indexes]) output.write(""" %s = %s %s """ % (tname, code, indexes)) # vim: expandtab tabstop=4 shiftwidth=4:
def _readgms(assy, filename, isInsert=False): """ Read the atoms from a GAMESS DAT file into a single new chunk, which is returned, unless there are no atoms in the file, in which case a warning is printed and None is returned. (The new chunk (if returned) is in assy, but is not yet added into any Group or Part in assy -- caller must do that.) """ fi = open(filename, "rU") lines = fi.readlines() fi.close() dir, nodename = os.path.split(filename) ndix = {} mol = Chunk(assy, nodename) countdown = 0 equilibruim_found = False atoms_found = False for card in lines: if failpat.search( card): # GAMESS Aborted. No atom data will be found. print card break # If this card is found: # "1 ***** EQUILIBRIUM GEOMETRY LOCATED *****\n" # we know we have a successfully optimized structure/set of atoms. # If this card is not found, the optimization failed for some reason. # Atom positions begin soon after this card. if card == "1 ***** EQUILIBRIUM GEOMETRY LOCATED *****\n": equilibruim_found = True continue # The atom positions we want ALWAYS begin 2 lines after this card: # " COORDINATES OF ALL ATOMS ARE (ANGS)\n" # which follows the previous card. # This is one way to fix the problem mentioned above. # I've commented the code below out since it needs further work to do what # we need, and there is a chance we will not need this if GAMESS-US has # the same number of lines (6) after the "EQUILIBRIUM" card above. # # P.S. The reason we do not just look for this card by itself is that there # can be many of them. There is only one "EQUILIBRIUM" card, and the # good atoms follow that card. # 050624 Mark if equilibruim_found: if card == " COORDINATES OF ALL ATOMS ARE (ANGS)\n": atoms_found = True reading_atoms = True countdown = 2 continue if not equilibruim_found or not atoms_found: continue if countdown: countdown -= 1 # print countdown, card # for debugging only. continue # The current card contains atom type and position. n = 0 if reading_atoms: if len(card) < 10: reading_atoms = False # Finished reading atoms. break m = irecpat.match(card) sym = capitalize(m.group(1)) try: PeriodicTable.getElement(sym) except: env.history.message( redmsg( "Warning: GAMESS DAT file: unknown element %s in: %s" % (sym, card))) else: xyz = map(float, (m.group(2), m.group(3), m.group(4))) a = Atom(sym, A(xyz), mol) ndix[n] = a n += 1 # Don't return an empty chunk. if not mol.atoms: msg = "Warning: GAMESS file contains no equilibrium geometry. No atoms read into part." env.history.message(redmsg(msg)) return None # Need to compute and add bonds for this chunk. I'll ask Bruce how to best accomplish this. # In the meantime, let's warn the user that no bonds have been formed since it # is impossible to see this in vdW display mode. # Mark 050623. msg = "Warning: Equilibrium geometry found. Atoms read into part, but there are no bonds." env.history.message(orangemsg(msg)) return mol
def _get_shape(self): return string.capitalize(self.getAttribute("SHAPE"))
def _get_align(self): return string.capitalize(self.getAttribute("ALIGN"))
def getInventory(self, queryTerms): keys = queryTerms.keys() isbnSelect = "" kindSelect = "" statusSelect = "" titleSelect = "" authorSelect = "" categorySelect = "" clauseTables = [] if "kind" in keys: # joins suck, avoid if possible kind_map = {} for k in [(x.kindName, x.id) for x in list(Kind.select())]: kind_map[k[0]] = k[1] try: kind_id = kind_map[queryTerms['kind']] kindSelect = Book.sqlrepr( AND( Field("book", "title_id") == Field("title", "id"), Field("title", "kind_id") == kind_id)) except: pass if 'status' in keys: statusSelect = Book.sqlrepr( Field("book", "status") == queryTerms["status"]) if ('title' in keys) or ('authorName' in keys) or ('kind' in keys) or ( 'categoryName' in keys) or ('isbn' in keys): clauseTables.append('title') #we are going to need to do a join if 'title' in keys: titleSelect = Book.sqlrepr( AND( Field("book", "title_id") == Field("title", "id"), RLIKE(Field("title", "booktitle"), queryTerms["title"]))) if 'isbn' in keys: titleSelect = Book.sqlrepr( AND( Field("book", "title_id") == Field("title", "id"), Field("title", "isbn") == queryTerms["isbn"])) if 'authorName' in keys: #~ authorSelect="""book.title_id = title.id AND author.title_id=title.id AND author.author_name RLIKE %s""" % (Book.sqlrepr(queryTerms["authorName"])) authorSelect = Book.sqlrepr( AND( Field("book", "title_id") == Field("title", "id"), Field("author", "id") == Field("author_title", "author_id"), Field("title", "id") == Field("author_title", "title_id"), RLIKE(Field("author", "author_name"), queryTerms["authorName"]))) clauseTables.append('author') clauseTables.append('author_title') if 'categoryName' in keys: #~ categorySelect="""book.title_id = title.id AND category.title_id=title.id AND category.category_name RLIKE %s""" % (Book.sqlrepr(queryTerms["categoryName"])) categorySelect = Book.sqlrepr( AND( Field("book", "title_id") == Field("title", "id"), Field("category", "title_id") == Field("title", "id"), RLIKE(Field("category", "category_name"), queryTerms["categoryName"]))) clauseTables.append('category') # At this time, ubuntu install sqlobject 0.6.1 if apt-get install python2.4-sqlobject, # which make the search crash, since the distinct attribute is defined somewhere after 0.6.1 try: books = Book.select(string.join([ term for term in [ statusSelect, titleSelect, authorSelect, kindSelect, categorySelect ] if term != "" ], " AND "), clauseTables=clauseTables, distinct=True) except TypeError: books = Book.select(string.join([ term for term in [ statusSelect, titleSelect, authorSelect, kindSelect, categorySelect ] if term != "" ], " AND "), clauseTables=clauseTables) results = {} i = 1 for b in books: theTitle = b.title.booktitle.decode("unicode_escape") if b.notes == None: b.notes = "" authorString = string.join([ a.author_name.decode("unicode_escape") for a in b.title.author ], ",") results[i] = (string.capitalize(theTitle), authorString, b.listprice, b.title.publisher.decode("unicode_escape"), b.status.decode("unicode_escape"), b.title.isbn, b.distributor.decode("unicode_escape"), b.notes.decode("unicode_escape"), b.id, b.title.kind and b.title.kind.kindName or '') i = i + 1 return results
print round(100.10) print round(100.49) print round(100.50) # random 取随机数 print iii(1, 100) # help("random") # in 操作 print 'bc' in 'abcd' print 'n' in 'abcd' print 'nm' not in 'abcd' # string 模块 import string print string.capitalize("hello") print string.lowercase print "HELLO".lower() print string.split("asdadada asdada") print string.rstrip(" adsd ") print string.lstrip(" adsd ") print string.strip(" adsd ") # re 模块 import re # Python提供了两种不同的原始操作:match和search.match是从字符串的起点开始做匹配,而search是从字符串做任意匹配. m = re.search("^as+", "asdfabbbb") print m m = re.search("ab+", "asdfabbbb") print m print m.group()
def select(self, el): e = string.capitalize(el) self.c[e]['relief'] = RAISED self.c[e]['bg'] = self.color(e, sel=1)
1.字符串长度获取: len(str) 例: print '%s length=%d' % (s,len(s)) # 打印: python String function length=22 2.字母处理 全部大写: str.upper() 全部小写: str.lower() 大小写互换: str.swapcase() 首字母大写,其余小写: str.capitalize() 首字母大写(每个词都这样): str.title() print '%s lower=%s' % (s,s.lower()) # 打印: python String function lower=python string function print '%s upper=%s' % (s,s.upper()) # 打印: python String function upper=PYTHON STRING FUNCTION print '%s swapcase=%s' % (s,s.swapcase()) # 打印: python String function swapcase=PYTHON sTRING FUNCTION print '%s capitalize=%s' % (s,s.capitalize()) # 打印: python String function capitalize=Python string function print '%s title=%s' % (s,s.title()) # 打印: python String function title=Python String Function import string; print string.capitalize(s) # 打印: Python string function 3.格式化相关 获取固定长度,右对齐,左边不够用空格补齐: str.ljust(width) 获取固定长度,左对齐,右边不够用空格补齐: str.ljust(width) 获取固定长度,中间对齐,两边不够用空格补齐: str.ljust(width) 获取固定长度,右对齐,左边不足用0补齐 print '%s ljust="%s"' % (s,s.ljust(40)) # 打印: python String function ljust="python String function " print '%s rjust="%s"' % (s,s.rjust(40)) # 打印: python String function rjust=" python String function" print '%s center="%s"' % (s,s.center(40)) # 打印: python String function center=" python String function " print '%s zfill="%s"' % (s,s.zfill(40)) # 打印: python String function zfill="000000000000000000python String function" import string; print string.zfill(s, 40) # 打印: 000000000000000000python String function
import types try: language = getConfigExpress().GetString('language', 'english') checkLanguage = getConfigExpress().GetBool('check-language', 1) except: language = simbase.config.GetString('language', 'english') checkLanguage = simbase.config.GetBool('check-language', 1) def getLanguage(): return language print 'PLocalizer: Running in language: %s' % language _languageModule = 'pirates.piratesbase.PLocalizer' + string.capitalize( language) _questStringModule = 'pirates.piratesbase.PQuestStrings' + string.capitalize( language) _greetingStringModule = 'pirates.piratesbase.PGreetingStrings' + string.capitalize( language) _dialogStringModule = 'pirates.piratesbase.PDialogStrings' + string.capitalize( language) exec 'from ' + _languageModule + ' import *' exec 'from ' + _questStringModule + ' import *' exec 'from ' + _greetingStringModule + ' import *' exec 'from ' + _dialogStringModule + ' import *' if checkLanguage: l = {} g = {} englishModule = __import__('pirates.piratesbase.PLocalizerEnglish', g, l) foreignModule = __import__(_languageModule, g, l)
def camelcase(value): return "".join( [capitalize(w) for w in re.split(re.compile("[\W_]*"), value)])
def _get_vAlign(self): return string.capitalize(self.getAttribute('VALIGN'))
else: jfile.write(' public ' + jtype + '[] ' + varstring + ';\n') #if builtin_type == 0: if jtype != 'char': if arraysize.isdigit(): jclass_constructor += ' ' + varstring + ' = new ' + jtype + '[' + arraysize + '];\n' else: jclass_constructor += ' ' + varstring + ' = new ' + jtype + '[playercore_javaConstants.' + arraysize + '];\n' else: arraysize = '' jfile.write(' public ' + jtype + ' ' + varstring + ';\n') if builtin_type == 0: jclass_constructor += ' ' + varstring + ' = new ' + jtype + '();\n' capvarstring = string.capitalize(varstring[0]) + varstring[1:] if builtin_type: pcj_data_to_jdata += ' Jdata.' + varstring + ' = data.get' + capvarstring + '();\n' pcj_jdata_to_data += ' data.set' + capvarstring + '(Jdata.' + varstring +');\n' else: if arraysize == '': pcj_data_to_jdata += ' Jdata.' + varstring + ' = ' + type + '_to_' + jtype + '(data.get' + capvarstring + '());\n' pcj_jdata_to_data += ' data.set' + capvarstring + '(' + jtype + '_to_' + type + '(Jdata.' + varstring + '));\n' else: try: asize = int(arraysize) except: arraysize = 'playercore_javaConstants.' + arraysize pcj_data_to_jdata += ' {\n' pcj_data_to_jdata += ' ' + type + ' foo[] = data.get' + capvarstring + '();\n' pcj_data_to_jdata += ' for(int i=0;i<' + arraysize + ';i++)\n'
def __init__(self, name, datatype): self.name = name self.datatype = string.capitalize(string.lower(datatype)) self.references = [] self.uniqueCons = []
language = getConfigExpress().GetString("language", "english") checkLanguage = getConfigExpress().GetBool("check-language", 0) except: # AI language = simbase.config.GetString("language", "english") checkLanguage = simbase.config.GetBool("check-language", 0) # Ask what language we are running in. Returns a string. def getLanguage(): return language print("TTLocalizer: Running in language: %s" % (language)) if language == 'english': _languageModule = "toontown.toonbase.TTLocalizer" + string.capitalize( language) else: checkLanguage = 1 _languageModule = "toontown.toonbase.TTLocalizer_" + language print("from " + _languageModule + " import *") exec("from " + _languageModule + " import *") if checkLanguage: l = {} g = {} englishModule = __import__("toontown.toonbase.TTLocalizerEnglish", g, l) foreignModule = __import__(_languageModule, g, l) for key, val in englishModule.__dict__.items(): if not foreignModule.__dict__.has_key(key): print("WARNING: Foreign module: %s missing key: %s" %
def FlexTargetName(ext): """Flex requires CamelCase.as""" name = PROTO_EXT_RE.sub(ext, self.GetShortName()) name = "".join([capitalize(w) for w in name.split('_')]) return util.PathToName(os.path.join(self.GetBuildDirectory(), name))
"""