code stringlengths 1 18.2k |
|---|
def is_url(text): """ Check if the given text looks like a URL. """ if text is None: return False text = text.lower() return text.startswith('http://') or text.startswith('https://') or \ text.startswith('urn:') or text.startswith('file://') |
def safe_uriref(text): """ Escape a URL properly. """ url_ = url.parse(text).sanitize().deuserinfo().canonical() return URIRef(url_.punycode().unicode()) |
def job_stats_enhanced(job_id): """ Get full job and step stats for job_id """ stats_dict = {} with os.popen('qstat -xf ' + str(job_id)) as f: try: line = f.readline().strip() while line: if line.startswith('Job Id:'): stats_dict['job_id'] = line.split(':')[1].split('.')[0].strip() elif line.startswith('resources_used.... |
cols[2] stats_dict['status'] = cols[9] stats_dict['wallclock'] = get_timedelta(cols[10]) return stats_dict except Exception as e: print(e) print('PBS: Error reading job stats') stats_dict['status'] = 'UNKNOWN' return stats_dict |
def getOrigin(self, cartesian=False): """Return the ra/decs of the channel corners if the S/C is pointed at the origin (ra,dec = 0,0) Inputs: cartesian (bool) If True, return each channel corner as a unit vector Returns: A 2d numpy array. Each row represents a channel corner The columns are module, output, channel, ra,... |
def computePointing(self, ra_deg, dec_deg, roll_deg, cartesian=False): """Compute a pointing model without changing the internal object pointing""" # Roll FOV Rrotate = r.rotateInXMat(roll_deg) # Roll # Slew from ra/dec of zero Ra = r.rightAscensionRotationMatrix(ra_deg) Rd = r.declinationRotationMatrix(dec_deg) Rslew ... |
def getRaDecs(self, mods): """Internal function converting cartesian coords to ra dec""" raDecOut = np.empty( (len(mods), 5)) raDecOut[:,0:3] = mods[:,0:3] for i, row in enumerate(mods): raDecOut[i, 3:5] = r.raDecFromVec(row[3:6]) return raDecOut |
def isOnSiliconList(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING): """similar to isOnSilicon() but takes lists as input""" ch, col, row = self.getChannelColRowList(ra_deg, dec_deg) out = np.zeros(len(ch), dtype=bool) for channel in set(ch): mask = (ch == channel) if channel in self.brokenChannels: continue if cha... |
def getChannelColRowList(self, ra, dec, wantZeroOffset=False, allowIllegalReturnValues=True): """similar to getChannelColRow() but takes lists as input""" try: ch = self.pickAChannelList(ra, dec) except ValueError: logger.warning("WARN: %.7f %.7f not on any channel" % (ra, dec)) return (0, 0, 0) col = np.zeros(len(ch))... |
def pickAChannelList(self, ra_deg, dec_deg): """Similar to pickAChannel() but takes lists as input. This will require AstroPy to be installed. """ try: from astropy.coordinates import SkyCoord from astropy import units as u except ImportError: raise ImportError("AstroPy needs to be installed to use this feature.") cRa ... |
def colRowIsOnSciencePixelList(self, col, row, padding=DEFAULT_PADDING): """similar to colRowIsOnSciencePixelList() but takes lists as input""" out = np.ones(len(col), dtype=bool) col_arr = np.array(col) row_arr = np.array(row) mask = np.bitwise_or(col_arr < 12. - padding, col_arr > 1111 + padding) out[mask] = False ma... |
def isOnSilicon(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING): """Returns True if the given location is observable with a science CCD. Parameters ---------- ra_deg : float Right Ascension (J2000) in decimal degrees. dec_deg : float Declination (J2000) in decimal degrees. padding : float Objects <= this many pixel... |
def getChannelColRow(self, ra, dec, wantZeroOffset=False, allowIllegalReturnValues=True): """Returns (channel, column, row) given an (ra, dec) coordinate. Returns (0, 0, 0) or a ValueError if the coordinate is not on silicon. """ try: ch = self.pickAChannel(ra, dec) except ValueError: logger.warning("WARN: %.7f %.7f no... |
def pickAChannel(self, ra_deg, dec_deg): """Returns the channel number closest to a given (ra, dec) coordinate. """ # Could improve speed by doing this in the projection plane # instead of sky coords cRa = self.currentRaDec[:, 3] # Ra of each channel corner cDec = self.currentRaDec[:, 4] # dec of each channel corner di... |
def getColRowWithinChannel(self, ra, dec, ch, wantZeroOffset=False, allowIllegalReturnValues=True): """Returns (col, row) given a (ra, dec) coordinate and channel number. """ # How close is a given ra/dec to the origin of a KeplerModule? x, y = self.defaultMap.skyToPix(ra, dec) kepModule = self.getChannelAsPolygon(ch) ... |
fov.txt col = colFrac*(1106-17) + 17 row = rowFrac*(1038-25) + 25 if not allowIllegalReturnValues: if not self.colRowIsOnSciencePixel(col, row): msg = "Request position %7f %.7f " % (ra, dec) msg += "does not lie on science pixels for channel %i " % (ch) msg += "[ %.1f %.1f]" % (col, row) raise ValueError(msg) # Conver... |
def colRowIsOnSciencePixel(self, col, row, padding=DEFAULT_PADDING): """Is col row on a science pixel? Ranges taken from Fig 25 or Instrument Handbook (p50) Padding allows for the fact that distortion means the results from getColRowWithinChannel can be off by a bit. Setting padding > 0 means that objects that are comp... |
def colRowIsOnFgsPixel(self, col, row, padding=-50): """Is col row on a science pixel? #See Kepler Flight Segment User's Manual (SP0039-702) \S 5.4 (p88) Inputs: col, row (floats or ints) padding If padding <0, pixel must be on silicon and this many pixels away from the edge of the CCD to return True Returns: boolean "... |
def getAllChannelsAsPolygons(self, maptype=None): """Return slew the telescope and return the corners of the modules as Polygon objects. If a projection is supplied, the ras and decs are mapped onto x, y using that projection """ polyList = [] for ch in self.origin[:, 2]: poly = self.getChannelAsPolygon(ch, maptype) po... |
def plotPointing(self, maptype=None, colour='b', mod3='r', showOuts=True, **kwargs): """Plot the FOV """ if maptype is None: maptype=self.defaultMap radec = self.currentRaDec for ch in radec[:,2][::4]: idx = np.where(radec[:,2].astype(np.int) == ch)[0] idx = np.append(idx, idx[0]) #% points to draw a box c = colour if ... |
def plotOutline(self, maptype=None, colour='#AAAAAA', **kwargs): """Plot an outline of the FOV. """ if maptype is None: maptype=self.defaultMap xarr = [] yarr = [] radec = self.currentRaDec for ch in [20,4,11,28,32, 71,68, 84, 75, 60, 56, 15 ]: idx = np.where(radec[:,2].astype(np.int) == ch)[0] idx = idx[0] #Take on th... |
def plotSpacecraftYAxis(self, maptype=None): """Plot a line pointing in the direction of the spacecraft y-axis (i.e normal to the solar panel """ if maptype is None: maptype=self.defaultMap #Plot direction of spacecraft +y axis. The subtraction of #90 degrees accounts for the different defintions of where #zero roll is... |
def plotChIds(self, maptype=None, modout=False): """Print the channel numbers on the plotting display Note: --------- This method will behave poorly if you are plotting in mixed projections. Because the channel vertex polygons are already projected using self.defaultMap, applying this function when plotting in a differ... |
def isPointInside(self, xp, yp): """Is the given point inside the polygon? Input: ------------ xp, yp (floats) Coordinates of point in same units that array vertices are specified when object created. Returns: ----------- **True** / **False** """ point = np.array([xp, yp]).transpose() polygon = self.polygon numVert, nu... |
def draw(self, **kwargs): """Draw the polygon Optional Inputs: ------------ All optional inputs are passed to ``matplotlib.patches.Polygon`` Notes: --------- Does not accept maptype as an argument. """ ax = mp.gca() shape = matplotlib.patches.Polygon(self.polygon, **kwargs) ax.add_artist(shape) |
def identifyModule(self, modout=False): """Write the name of a channel/modout on a plot Optional Inputs: ----------- modout (boolean). If True, write module and output. Otherwise write channel number Returns: ------------ **None** Output: ----------- Channel numbers are written to the current axis. """ x,y = np.mean(se... |
def parse_response(self, response, header=None): """Parses the response message. The following graph shows the structure of response messages. :: +----------+ +--+ data sep +<-+ | +----------+ | | | +--------+ +------------+ | +------+ | +-->| header +------->+ header sep +---+--->+ data +----+----+ | +--------+ +-----... |
def trigger(self, transport): """Triggers the transport.""" logger.debug('IEC60488 trigger') with transport: try: transport.trigger() except AttributeError: trigger_msg = self.create_message('*TRG') transport.write(trigger_msg) |
def clear(self, transport): """Issues a device clear command.""" logger.debug('IEC60488 clear') with transport: try: transport.clear() except AttributeError: clear_msg = self.create_message('*CLS') transport.write(clear_msg) |
def query_bytes(self, transport, num_bytes, header, *data): """Queries for binary data :param transport: A transport object. :param num_bytes: The exact number of data bytes expected. :param header: The message header. :param data: Optional data. :returns: The raw unparsed data bytearray. """ message = self.create_mess... |
def raDecFromVec(v): """ Taken from http://www.math.montana.edu/frankw/ccp/multiworld/multipleIVP/spherical/learn.htm Search for "convert from Cartestion to spherical coordinates" Adapted because I'm dealing with declination which is defined with 90degrees at zenith """ #Ensure v is a normal vector v /= np.linalg.norm(... |
def rotateAroundVector(v1, w, theta_deg): """Rotate vector v1 by an angle theta around w Taken from https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation (see Section "Rotating a vector") Notes: Rotating the x axis 90 degrees about the y axis gives -z Rotating the x axis 90 degrees about the z axis gives +y "... |
def rotateInDeclination(v1, theta_deg): """Rotation is chosen so a rotation of 90 degrees from zenith ends up at ra=0, dec=0""" axis = np.array([0,-1,0]) return rotateAroundVector(v1, axis, theta_deg) |
def declinationRotationMatrix(theta_deg): """Construct the rotation matrix for a rotation of the declination coords (i.e around the axis of ra=90, dec=0) Taken from Section 3.3 of Arfken and Weber (Eqn 3.91) Modfied the signs of the sines so that a rotation of the zenith vector by 90 degrees ends up at ra, dec = 0,0 ""... |
def sweep(self, mode, speed=None): """Starts the output current sweep. :param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`, `'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well. :param speed: The sweeping speed. Valid entries are `'FAST'`, `'SLOW'` or `None`. """ sweep_modes = ['UP', 'DOWN', 'P... |
def run_on_main_thread(self, func, args=None, kwargs=None): """ Runs the ``func`` callable on the main thread, by using the provided microservice instance's IOLoop. :param func: callable to run on the main thread :param args: tuple or list with the positional arguments. :param kwargs: dict with the keyword arguments. :... |
def rotateAboutVectorMatrix(vec, theta_deg): """Construct the matrix that rotates vector a about vector vec by an angle of theta_deg degrees Taken from http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Input: theta_deg (float) Angle through which vectors should be rotated in degrees Retur... |
ufunny return term1 + term2 + term3 |
def rotateInZMat(theta_deg): """Rotate a vector theta degrees around the z-axis Equivalent to yaw left Rotates the vector in the sense that the x-axis is rotated towards the y-axis. If looking along the z-axis (which is not the way you usually look at it), the vector rotates clockwise. If sitting on the vector [1,0,0],... |
def urlize_tweet(tweet): """ Turn #hashtag and @username in a text to Twitter hyperlinks, similar to the ``urlize()`` function in Django. Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag. Should be used before urlize_tweet """ if tweet['retweeted']: text = 'RT {user}: {text}'.format( u... |
def getReadSession(self): ''' return scopted session ''' if self.ReadSession is None: self.ReadSession=scoped_session(sessionmaker(bind=self.engine)) return self.ReadSession |
def getWriteSession(self): ''' return unscope session, TODO, make it clear ''' if self.WriteSession is None: self.WriteSession=sessionmaker(bind=self.engine) self.writeSession=self.WriteSession() return self.writeSession |
def readTupleQuotes(self, symbol, start, end): ''' read quotes as tuple ''' if end is None: end=sys.maxint session=self.getReadSession()() try: rows=session.query(Quote).filter(and_(Quote.symbol == symbol, Quote.time >= int(start), Quote.time < int(end))) finally: self.getReadSession().remove() return rows |
def readBatchTupleQuotes(self, symbols, start, end): ''' read batch quotes as tuple to save memory ''' if end is None: end=sys.maxint ret={} session=self.getReadSession()() try: symbolChunks=splitListEqually(symbols, 100) for chunk in symbolChunks: rows=session.query(Quote.symbol, Quote.time, Quote.close, Quote.volume,... |
def read_tuple_ticks(self, symbol, start, end): ''' read ticks as tuple ''' if end is None: end=sys.maxint session=self.getReadSession()() try: rows=session.query(Tick).filter(and_(Tick.symbol == symbol, Tick.time >= int(start), Tick.time < int(end))) finally: self.getReadSession().remove() return [self.__sqlToTupleTic... |
def write_quotes(self, quotes): ''' write quotes ''' if self.first: Base.metadata.create_all(self.engine, checkfirst=True) self.first=False session=self.getWriteSession() session.add_all([self.__quoteToSql(quote) for quote in quotes]) |
def write_ticks(self, ticks): ''' write ticks ''' if self.first: Base.metadata.create_all(self.engine, checkfirst=True) self.first=False session=self.getWriteSession() session.add_all([self.__tickToSql(tick) for tick in ticks]) |
def write_fundamental(self, keyTimeValueDict): ''' write fundamental ''' if self.first: Base.metadata.create_all(self.__getEngine(), checkfirst=True) self.first=False sqls=self._fundamentalToSqls(keyTimeValueDict) session=self.Session() try: session.add_all(sqls) finally: self.Session.remove() |
def _fundamentalToSqls(self, symbol, keyTimeValueDict): ''' convert fundament dict to sqls ''' sqls=[] for key, timeValues in keyTimeValueDict.iteritems(): for timeStamp, value in timeValues.iteritems(): sqls.append(FmSql(symbol, key, timeStamp, value)) return sqls |
def delete(self): """Deletes the current curve. :raises RuntimeError: Raises when` when one tries to delete a read-only curve. """ if self._writeable: self._write(('CRVDEL', Integer), self.idx) else: raise RuntimeError('Can not delete read-only curves.') |
def line(self, idx): """Return the i'th program line. :param i: The i'th program line. """ # TODO: We should parse the response properly. return self._query(('PGM?', [Integer, Integer], String), self.idx, idx) |
def append_line(self, new_line): """Appends the new_line to the LS340 program.""" # TODO: The user still has to write the raw line, this is error prone. self._write(('PGM', [Integer, String]), self.idx, new_line) |
def softcal(self, std, dest, serial, T1, U1, T2, U2, T3=None, U3=None): """Generates a softcal curve. :param std: The standard curve index used to calculate the softcal curve. Valid entries are 1-20 :param dest: The user curve index where the softcal curve is stored. Valid entries are 21-60. :param serial: The serial n... |
(T3 is not None) and (U3 is not None): args.extend([T3, U3]) dtype.extend([Float, Float]) self._write(('SCAL', dtype), *args) |
def makeThumbnail(inputFile, outputFile, thumbnailSize, outputFormat='jpeg'): """ Make a thumbnail of the image stored at C{inputPath}, preserving its aspect ratio, and write the result to C{outputPath}. @param inputFile: The image file (or path to the file) to thumbnail. @type inputFile: C{file} or C{str} @param outpu... |
otherwise PIL silently switches to Image.NEAREST sampling. if image.mode == '1': image = image.convert('L') elif image.mode == 'P': image = image.convert('RGB') image.thumbnail((thumbnailSize, thumbnailSize), Image.ANTIALIAS) image.save(outputFile, outputFormat) |
def _descriptiveIdentifier(contactType): """ Get a descriptive identifier for C{contactType}, taking into account the fact that it might not have implemented the C{descriptiveIdentifier} method. @type contactType: L{IContactType} provider. @rtype: C{unicode} """ descriptiveIdentifierMethod = getattr( contactType, 'desc... |
def _organizerPluginName(plugin): """ Get a name for C{plugin}, taking into account the fact that it might not have defined L{IOrganizerPlugin.name}. @type plugin: L{IOrganizerPlugin} provider. @rtype: C{unicode} """ name = getattr(plugin, 'name', None) if name is not None: return name warn( "IOrganizerPlugin now has t... |
def _stringifyKeys(d): """ Return a copy of C{d} with C{str} keys. @type d: C{dict} with C{unicode} keys. @rtype: C{dict} with C{str} keys. """ return dict((k.encode('ascii'), v) for (k, v) in d.iteritems()) |
def mugshot1to2(old): """ Upgrader for L{Mugshot} from version 1 to version 2, which sets the C{smallerBody} attribute to the path of a smaller mugshot image. """ smallerBody = Mugshot.makeThumbnail(old.body.open(), old.person, old.type.split('/')[1], smaller=True) return old.upgradeVersion(Mugshot.typeName, 1, 2, pers... |
def mugshot2to3(old): """ Upgrader for L{Mugshot} from version 2 to version 3, which re-thumbnails the mugshot to take into account the new value of L{Mugshot.smallerSize}. """ new = old.upgradeVersion(Mugshot.typeName, 2, 3, person=old.person, type=old.type, body=old.body, smallerBody=old.smallerBody) new.smallerBody ... |
def getParameters(self, contactItem): """ Return a list containing a single parameter suitable for changing the VIP status of a person. @type contactItem: L{_PersonVIPStatus} @rtype: C{list} of L{liveform.Parameter} """ isVIP = False # default if contactItem is not None: isVIP = contactItem.person.vip return [liveform.... |
def getParameters(self, emailAddress): """ Return a C{list} of one L{LiveForm} parameter for editing an L{EmailAddress}. @type emailAddress: L{EmailAddress} or C{NoneType} @param emailAddress: If not C{None}, an existing contact item from which to get the email address default value. @rtype: C{list} @return: The parame... |
def _existing(self, email): """ Return the existing L{EmailAddress} item with the given address, or C{None} if there isn't one. """ return self.store.findUnique( EmailAddress, EmailAddress.address == email, default=None) |
def createContactItem(self, person, email): """ Create a new L{EmailAddress} associated with the given person based on the given email address. @type person: L{Person} @param person: The person with whom to associate the new L{EmailAddress}. @type email: C{unicode} @param email: The value to use for the I{address} attr... |
def getContactItems(self, person): """ Return all L{EmailAddress} instances associated with the given person. @type person: L{Person} """ return person.store.query( EmailAddress, EmailAddress.person == person) |
def editContactItem(self, contact, email): """ Change the email address of the given L{EmailAddress} to that specified by C{email}. @type email: C{unicode} @param email: The new value to use for the I{address} attribute of the L{EmailAddress}. @return: C{None} """ address = self._existing(email) if address is not None ... |
def getEmailAddresses(self): """ Return an iterator of all email addresses associated with this person. @return: an iterator of unicode strings in RFC2822 address format. """ return self.store.query( EmailAddress, EmailAddress.person == self).getColumn('address') |
def getMugshot(self): """ Return the L{Mugshot} associated with this L{Person}, or an unstored L{Mugshot} pointing at a placeholder mugshot image. """ mugshot = self.store.findUnique( Mugshot, Mugshot.person == self, default=None) if mugshot is not None: return mugshot return Mugshot.placeholderForPerson(self) |
def _makeStoreOwnerPerson(self): """ Make a L{Person} representing the owner of the store that this L{Organizer} is installed in. @rtype: L{Person} """ if self.store is None: return None userInfo = self.store.findFirst(signup.UserInfo) name = u'' if userInfo is not None: name = userInfo.realName account = self.store.fi... |
def _gatherPluginMethods(self, methodName): """ Walk through each L{IOrganizerPlugin} powerup, yielding the bound method if the powerup implements C{methodName}. Upon encountering a plugin which fails to implement it, issue a L{PendingDeprecationWarning}. @param methodName: The name of a L{IOrganizerPlugin} method. @ty... |
def _checkContactType(self, contactType): """ Possibly emit some warnings about C{contactType}'s implementation of L{IContactType}. @type contactType: L{IContactType} provider """ if getattr(contactType, 'getEditFormForPerson', None) is None: warn( "IContactType now has the 'getEditFormForPerson'" " method, but %s did ... |
def getContactTypes(self): """ Return an iterator of L{IContactType} providers available to this organizer's store. """ yield VIPPersonContactType() yield EmailContactType(self.store) yield PostalContactType() yield PhoneNumberContactType() yield NotesContactType() for getContactTypes in self._gatherPluginMethods('getC... |
def getPeopleFilters(self): """ Return an iterator of L{IPeopleFilter} providers available to this organizer's store. """ yield AllPeopleFilter() yield VIPPeopleFilter() for getPeopleFilters in self._gatherPluginMethods('getPeopleFilters'): for peopleFilter in getPeopleFilters(): yield peopleFilter for tag in sorted(se... |
def getPeopleTags(self): """ Return a sequence of tags which have been applied to L{Person} items. @rtype: C{set} """ query = self.store.query( Tag, Tag.object == Person.storeID) return set(query.getColumn('name').distinct()) |
def groupReadOnlyViews(self, person): """ Collect all contact items from the available contact types for the given person, organize them by contact group, and turn them into read-only views. @type person: L{Person} @param person: The person whose contact items we're interested in. @return: A mapping of of L{ContactGrou... |
so this method can't be "groupContactItems" (which # seems to make more sense), unless it returned some weird data # structure which managed to associate contact items and contact # types. grouped = {} for contactType in self.getContactTypes(): for contactItem in contactType.getContactItems(person): contactGroup = cont... |
def getContactCreationParameters(self): """ Yield a L{Parameter} for each L{IContactType} known. Each yielded object can be used with a L{LiveForm} to create a new instance of a particular L{IContactType}. """ for contactType in self.getContactTypes(): if contactType.allowMultipleContactItems: descriptiveIdentifier = _... |
def _parametersToDefaults(self, parameters): """ Extract the defaults from C{parameters}, constructing a dictionary mapping parameter names to default values, suitable for passing to L{ListChangeParameter}. @type parameters: C{list} of L{liveform.Parameter} or L{liveform.ChoiceParameter}. @rtype: C{dict} """ defaults =... |
def toContactEditorialParameter(self, contactType, person): """ Convert the given contact type into a L{liveform.LiveForm} parameter. @type contactType: L{IContactType} provider. @type person: L{Person} @rtype: L{liveform.Parameter} or similar. """ contactItems = list(contactType.getContactItems(person)) if contactType... |
def getContactEditorialParameters(self, person): """ Yield L{LiveForm} parameters to edit each contact item of each contact type for the given person. @type person: L{Person} @return: An iterable of two-tuples. The first element of each tuple is an L{IContactType} provider. The third element of each tuple is the L{Live... |
def createPerson(self, nickname, vip=_NO_VIP): """ Create a new L{Person} with the given name in this organizer. @type nickname: C{unicode} @param nickname: The value for the new person's C{name} attribute. @type vip: C{bool} @param vip: Value to set the created person's C{vip} attribute to (deprecated). @rtype: L{Pers... |
def createContactItem(self, contactType, person, contactInfo): """ Create a new contact item for the given person with the given contact type. Broadcast a creation to all L{IOrganizerPlugin} powerups. @type contactType: L{IContactType} @param contactType: The contact type which will be used to create the contact item. ... |
def editContactItem(self, contactType, contactItem, contactInfo): """ Edit the given contact item with the given contact type. Broadcast the edit to all L{IOrganizerPlugin} powerups. @type contactType: L{IContactType} @param contactType: The contact type which will be used to edit the contact item. @param contactItem: ... |
def _callOnOrganizerPlugins(self, methodName, *args): """ Call a method on all L{IOrganizerPlugin} powerups on C{self.store}, or emit a deprecation warning for each one which does not implement that method. """ for observer in self.getOrganizerPlugins(): method = getattr(observer, methodName, None) if method is not Non... |
def editPerson(self, person, nickname, edits): """ Change the name and contact information associated with the given L{Person}. @type person: L{Person} @param person: The person which will be modified. @type nickname: C{unicode} @param nickname: The new value for L{Person.name} @type edits: C{list} @param edits: list o... |
submission) |
def personByName(self, name): """ Retrieve the L{Person} item for the given Q2Q address, creating it first if necessary. @type name: C{unicode} """ return self.store.findOrCreate(Person, organizer=self, name=name) |
def personByEmailAddress(self, address): """ Retrieve the L{Person} item for the given email address (or return None if no such person exists) @type name: C{unicode} """ email = self.store.findUnique(EmailAddress, EmailAddress.address == address, default=None) if email is not None: return email.person |
def urlForViewState(self, person, viewState): """ Return a url for L{OrganizerFragment} which will display C{person} in state C{viewState}. @type person: L{Person} @type viewState: L{ORGANIZER_VIEW_STATES} constant. @rtype: L{url.URL} """ # ideally there would be a more general mechanism for encoding state # like this ... |
def filterByFilter(self, filterName): """ Swap L{baseConstraint} with the result of calling L{IPeopleFilter.getPeopleQueryComparison} on the named filter. @type filterName: C{unicode} """ filter = self.filters[filterName] self.baseConstraint = filter.getPeopleQueryComparison(self.store) |
def contactInfo(self, request, tag): """ Render the result of calling L{IContactType.getReadOnlyView} on the corresponding L{IContactType} for each piece of contact info associated with L{person}. Arrange the result by group, using C{tag}'s I{contact-group} pattern. Groupless contact items will have their views yielded... |
def pluginTabbedPane(self, request, tag): """ Render a L{tabbedPane.TabbedPaneFragment} with an entry for each item in L{plugins}. """ iq = inevow.IQ(tag) tabNames = [ _organizerPluginName(p).encode('ascii') # gunk for p in self.plugins] child = tabbedPane.TabbedPaneFragment( zip(tabNames, ([self.getPluginWidget(tabNam... |
def getPluginWidget(self, pluginName): """ Return the named plugin's view. @type pluginName: C{unicode} @param pluginName: The name of the plugin. @rtype: L{LiveElement} """ # this will always pick the first plugin with pluginName if there is # more than one. don't do that. for plugin in self.plugins: if _organizerPlug... |
def beforeRender(self, ctx): """ Implement this hook to initialize the L{initialPerson} and L{initialState} slots with information from the request url's query args. """ # see the comment in Organizer.urlForViewState which suggests an # alternate implementation of this kind of functionality. request = inevow.IRequest(c... |
def getInitialArguments(self): """ Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of L{initialPerson} and the value of L{initialState}, if they are set. """ initialArguments = (self.organizer.storeOwnerPerson.name,) if self.initialPerson is not None: initialArguments += (self.initialPerson.name, self.i... |
def getAddPerson(self): """ Return an L{AddPersonFragment} which is a child of this fragment and which will add a person to C{self.organizer}. """ fragment = AddPersonFragment(self.organizer) fragment.setFragmentParent(self) return fragment |
def getImportPeople(self): """ Return an L{ImportPeopleWidget} which is a child of this fragment and which will add people to C{self.organizer}. """ fragment = ImportPeopleWidget(self.organizer) fragment.setFragmentParent(self) return fragment |
def getEditPerson(self, name): """ Get an L{EditPersonView} for editing the person named C{name}. @param name: A person name. @type name: C{unicode} @rtype: L{EditPersonView} """ view = EditPersonView(self.organizer.personByName(name)) view.setFragmentParent(self) return view |
def deletePerson(self, name): """ Delete the person named C{name} @param name: A person name. @type name: C{unicode} """ self.organizer.deletePerson(self.organizer.personByName(name)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.