code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if memo is None: memo = set() elif self in memo: # this is bad, but we have successfully detected and prevented the # only really bad symptom, an infinite loop. return memo.add(self) yield self for groupRole in self.store.q...
def allRoles(self, memo=None)
Identify all the roles that this role is authorized to act as. @param memo: used only for recursion. Do not pass this. @return: an iterator of all roles that this role is a member of, including itself.
7.736713
7.70964
1.003512
if shareID is None: shareID = genShareID(sharedItem.store) return Share(store=self.store, shareID=shareID, sharedItem=sharedItem, sharedTo=self, sharedInterfaces=interfaces)
def shareItem(self, sharedItem, shareID=None, interfaces=ALL_IMPLEMENTED)
Share an item with this role. This provides a way to expose items to users for later retrieval with L{Role.getShare}. @param sharedItem: an item to be shared. @param shareID: a unicode string. If provided, specify the ID under which the shared item will be shared. @param int...
3.807784
4.539914
0.838735
shares = list( self.store.query(Share, AND(Share.shareID == shareID, Share.sharedTo.oneOf(self.allRoles())))) interfaces = [] for share in shares: interfaces += share.sharedInterfaces if shares...
def getShare(self, shareID)
Retrieve a proxy object for a given shareID, previously shared with this role or one of its group roles via L{Role.shareItem}. @return: a L{SharedProxy}. This is a wrapper around the shared item which only exposes those interfaces explicitly allowed for the given role. @raise:...
7.660946
6.327467
1.210744
# XXX TODO #2371: this method really *should* be returning an L{IQuery} # provider as well, but that is kind of tricky to do. Currently, doing # queries leaks authority, because the resulting objects have stores # and "real" items as part of their interface; having this be a "r...
def asAccessibleTo(self, query)
@param query: An Axiom query describing the Items to retrieve, which this role can access. @type query: an L{iaxiom.IQuery} provider. @return: an iterable which yields the shared proxies that are available to the given role, from the given query.
10.798528
9.463763
1.14104
def get(self): if not self.sharedInterfaceNames: return () if self.sharedInterfaceNames == ALL_IMPLEMENTED_DB: I = implementedBy(self.sharedItem.__class__) L = list(I) T = tuple(L) return T ...
def sharedInterfaces()
This attribute is the public interface for code which wishes to discover the list of interfaces allowed by this Share. It is a list of Interface objects.
6.70577
6.008438
1.116059
date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, 1, 0, dt.tzinfo) if fmt is not None: return date.strftime(fmt) return date
def every_minute(dt=datetime.datetime.utcnow(), fmt=None)
Just pass on the given date.
2.173414
2.02615
1.072682
date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, 1, 1, 0, dt.tzinfo) if fmt is not None: return date.strftime(fmt) return date
def hourly(dt=datetime.datetime.utcnow(), fmt=None)
Get a new datetime object every hour.
2.471024
2.20427
1.121017
return date - datetime.timedelta(days=date.weekday())
def weekly(date=datetime.date.today())
Weeks start are fixes at Monday for now.
4.489641
3.467432
1.294803
return datetime.date(date.year, date.month, 1 if date.day < 15 else 15)
def biweekly(date=datetime.date.today())
Every two weeks.
3.442839
3.24054
1.062428
return datetime.date(date.year, date.month, 1)
def monthly(date=datetime.date.today())
Take a date object and return the first day of the month.
3.517475
2.367377
1.485812
return datetime.date(date.year, ((date.month - 1)//3) * 3 + 1, 1)
def quarterly(date=datetime.date.today())
Fixed at: 1/1, 4/1, 7/1, 10/1.
2.885535
2.731338
1.056455
return datetime.date(date.year, 1 if date.month < 7 else 7, 1)
def semiyearly(date=datetime.date.today())
Twice a year.
4.037339
3.939818
1.024753
f = self._collectionToLiveform() if f is not None: yield tags.fieldset[tags.legend[self.tab.name], f] for t in self.tab.children: f = inevow.IRenderer( self.collection.store.getItemByID(t.storeID)) f.tab = t if hasattr...
def fragments(self, req, tag)
Render our preference collection, any child preference collections we discover by looking at self.tab.children, and any fragments returned by its C{getSections} method. Subtabs and C{getSections} fragments are rendered as fieldsets inside the parent preference collection's tab.
5.930648
4.593515
1.291091
navigation = webnav.getTabs(self.aggregator.getPreferenceCollections()) pages = list() for tab in navigation: f = inevow.IRenderer( self.aggregator.store.getItemByID(tab.storeID)) f.tab = tab if hasattr(f, 'setFragmentParent'): ...
def tabbedPane(self, req, tag)
Render a tabbed pane tab for each top-level L{xmantissa.ixmantissa.IPreferenceCollection} tab
7.038363
6.053728
1.162649
if isAscending is None: isAscending = self.defaultSortAscending newSortColumn = self.columns[attributeID] if newSortColumn.sortAttribute() is None: raise Unsortable('column %r has no sort attribute' % (attributeID,)) if self.currentSortColumn == newSortC...
def resort(self, attributeID, isAscending=None)
Sort by one of my specified columns, identified by attributeID
4.547738
4.561396
0.997006
self._updateResults(self._sortAttributeValue(0), equalToStart=True, refresh=True) return self._currentResults
def currentPage(self)
Return a sequence of mappings of attribute IDs to column values, to display to the user. nextPage/prevPage will strive never to skip items whose column values have not been returned by this method. This is best explained by a demonstration. Let's say you have a table viewing a...
54.652954
35.604061
1.53502
if self._currentResults: pageStart = (self._currentResults[offset][ self.currentSortColumn.attributeID], self._currentResults[offset][ '__item__'].storeID) else: pageStart = None return pageStart
def _sortAttributeValue(self, offset)
return the value of the sort attribute for the item at 'offset' in the results of the last query, otherwise None.
12.143157
9.213587
1.317962
self.close_display() # Properly finish previous open_display() XkbIgnoreExtension(False) display_name = None major = c_int(XkbMajorVersion) minor = c_int(XkbMinorVersion) reason = c_int() self._display = XkbOpenDisplay( display_name, ...
def open_display(self)
Establishes connection with X server and prepares objects necessary to retrieve and send data.
4.478526
4.42755
1.011513
if hasattr(self, "_keyboard_description") and self._keyboard_description: names_mask = XkbSymbolsNameMask | XkbGroupNamesMask XkbFreeNames(self._keyboard_description, names_mask, True) XkbFreeControls(self._keyboard_description, XkbAllControlsMask, True) ...
def close_display(self)
Closes connection with X server and cleans up objects created on open_display().
4.214291
3.88564
1.084581
return _ListProxy(GroupData(num, name, symbol, variant) for (num, name, symbol, variant) in zip(range(self.groups_count), self.groups_names, self.groups_symbols, ...
def groups_data(self)
All data about all groups (get-only). :getter: Returns all data about all groups :type: list of GroupData
5.486013
5.851492
0.937541
if self._keyboard_description.contents.ctrls is not None: return self._keyboard_description.contents.ctrls.contents.num_groups else: groups_source = self._groups_source groups_count = 0 while (groups_count < XkbNumKbdGroups and ...
def groups_count(self)
Number of all groups (get-only). :getter: Returns number of all groups :type: int
6.60679
6.883785
0.959761
return _ListProxy(self._get_group_name_by_num(i) for i in range(self.groups_count))
def groups_names(self)
Names of all groups (get-only). :getter: Returns names of all groups :type: list of str
8.76416
9.817014
0.892752
return GroupData(self.group_num, self.group_name, self.group_symbol, self.group_variant)
def group_data(self)
All data about the current group (get-only). :getter: Returns all data about the current group :type: GroupData
6.698919
7.678243
0.872455
xkb_state = XkbStateRec() XkbGetState(self._display, XkbUseCoreKbd, byref(xkb_state)) return xkb_state.group
def group_num(self)
Current group number. :getter: Returns current group number :setter: Sets current group number :type: int
10.816319
13.831923
0.781982
s_mapping = {symdata.index: symdata.symbol for symdata in self._symboldata_list} return s_mapping[self.group_num]
def group_symbol(self)
Current group symbol. :getter: Returns current group symbol :setter: Sets current group symbol :type: str
9.267428
9.555734
0.969829
v_mapping = {symdata.index: symdata.variant for symdata in self._symboldata_list} return v_mapping[self.group_num] or ""
def group_variant(self)
Current group variant (get-only). :getter: Returns current group variant :type: str
14.154515
12.627769
1.120904
return format_str.format(**{ "num": self.group_num, "name": self.group_name, "symbol": self.group_symbol, "variant": self.group_variant, "current_data": self.group_data, "count": self.groups_count, "names": self.groups_...
def format(self, format_str)
Returns a formatted version of format_str. The only named replacement fields supported by this method and their corresponding API calls are: * {num} group_num * {name} group_name * {symbol} group_symbol * {variant} group_variant * ...
3.102109
1.627707
1.905816
if reg: x = dict((k, reg.get(k, d)) for k, d in default_reg.items()) else: x = dict(default_reg) return x
def _construct_register(reg, default_reg)
Constructs a register dict.
3.752316
3.106209
1.208005
if secondary is None: self._write(('*PCB', Integer(min=0, max=30)), primary) else: self._write( ('*PCB', [Integer(min=0, max=30), Integer(min=0, max=30)]), primary, secondary )
def pass_control_back(self, primary, secondary)
The address to which the controll is to be passed back. Tells a potential controller device the address to which the control is to be passed back. :param primary: An integer in the range 0 to 30 representing the primary address of the controller sending the command. :param ...
4.484486
4.147567
1.081233
if not host: raise ValueError("Host values of '' or None are not allowed.") timer = timing.Timer(timeout) while not timer.expired(): try: # Expect a free port, so use a small timeout Checker(timeout=0.1).assert_free(host, port) return except PortNotFree: # Politely wait. time.sleep(0.1) ra...
def free(host, port, timeout=float('Inf'))
Wait for the specified port to become free (dropping or rejecting requests). Return when the port is free or raise a Timeout if timeout has elapsed. Timeout may be specified in seconds or as a timedelta. If timeout is None or ∞, the routine will run indefinitely. >>> free('localhost', find_available_local_port()...
5.656327
5.59749
1.010511
infos = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM) family, proto, _, _, addr = next(iter(infos)) sock = socket.socket(family, proto) sock.bind(addr) addr, port = sock.getsockname()[:2] sock.close() return port
def find_available_local_port()
Find a free port on localhost. >>> 0 < find_available_local_port() < 65536 True
2.373809
2.386287
0.994771
if port is None and isinstance(host, abc.Sequence): host, port = host[:2] if platform.system() == 'Windows': host = client_host(host) info = socket.getaddrinfo( host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, ) list(itertools.starmap(self._connect, info))
def assert_free(self, host, port=None)
Assert that the given addr is free in that all attempts to connect fail within the timeout or raise a PortNotFree exception. >>> free_port = find_available_local_port() >>> Checker().assert_free('localhost', free_port) >>> Checker().assert_free('127.0.0.1', free_port) >>> Checker().assert_free('::1', free...
3.912815
4.324415
0.904819
ls = siteStore.findUnique(LoginSystem, default=None) if ls is None: try: raise UnsatisfiedRequirement() except UnsatisfiedRequirement: log.err(Failure(), "You have opened a substore from a site store with no " "LoginSystem. Me...
def _createLocalRouter(siteStore)
Create an L{IMessageRouter} provider for the default case, where no L{IMessageRouter} powerup is installed on the top-level store. It wraps a L{LocalMessageRouter} around the L{LoginSystem} installed on the given site store. If no L{LoginSystem} is present, this returns a null router which will si...
11.737366
7.648891
1.534519
self.consequence.answerReceived(self.answerValue, self.messageValue, self.sender, self.target) self.deleteFromStore()
def redeliver(self)
Re-deliver the answer to the consequence which previously handled it by raising an exception. This method is intended to be invoked after the code in question has been upgraded. Since there are no buggy answer receivers in production, nothing calls it yet.
15.850163
10.260895
1.544716
acct = self.loginSystem.accountByAddress(identifier.localpart, identifier.domain) return IMessageRouter(acct, None)
def _routerForAccount(self, identifier)
Locate an avatar by the username and domain portions of an L{Identifier}, so that we can deliver a message to the appropriate user.
14.962813
9.407502
1.590519
router = self._routerForAccount(target) if router is not None: router.routeMessage(sender, target, value, messageID) else: reverseRouter = self._routerForAccount(sender) reverseRouter.routeAnswer(sender, target, V...
def routeMessage(self, sender, target, value, messageID)
Implement L{IMessageRouter.routeMessage} by synchronously locating an account via L{axiom.userbase.LoginSystem.accountByAddress}, and delivering a message to it by calling a method on it.
5.185874
4.849002
1.069472
router = self._routerForAccount(originalSender) return router.routeAnswer(originalSender, originalTarget, value, messageID)
def routeAnswer(self, originalSender, originalTarget, value, messageID)
Implement L{IMessageRouter.routeMessage} by synchronously locating an account via L{axiom.userbase.LoginSystem.accountByAddress}, and delivering a response to it by calling a method on it and returning a deferred containing its answer.
5.533017
4.940248
1.119988
sched = IScheduler(self.store) if len(list(sched.scheduledTimes(self))) == 0: sched.schedule(self, sched.now())
def _scheduleMePlease(self)
This queue needs to have its run() method invoked at some point in the future. Tell the dependent scheduler to schedule it if it isn't already pending execution.
8.902435
7.518249
1.18411
avatarName = sender.localpart + u"@" + sender.domain # Look for the sender. answer = self.store.findUnique( _AlreadyAnswered, AND(_AlreadyAnswered.originalSender == sender, _AlreadyAnswered.messageID == messageID), default=None) ...
def routeMessage(self, sender, target, value, messageID)
Implement L{IMessageRouter.routeMessage} by locating a shared item which provides L{IMessageReceiver}, identified by L{target} in this L{MessageQueue}'s L{Store}, as shared to the specified C{sender}, then invoke its L{messageReceived} method. Then, take the results of that L{messageRec...
5.032728
4.545414
1.10721
router = self.siteRouter if answer.deliveryDeferred is None: d = answer.deliveryDeferred = router.routeAnswer( answer.originalSender, answer.originalTarget, answer.value, answer.messageID) def destroyAnswer(result): answer....
def _deliverAnswer(self, answer)
Attempt to deliver an answer to a message sent to this store, via my store's parent's L{IMessageRouter} powerup. @param answer: an L{AlreadyAnswered} that contains an answer to a message sent to this store.
5.978693
5.838404
1.024029
def txn(): qm = self._messageFromSender(originalSender, messageID) if qm is None: return c = qm.consequence if c is not None: c.answerReceived(value, qm.value, qm.sender, qm.target) ...
def routeAnswer(self, originalSender, originalTarget, value, messageID)
Route an incoming answer to a message originally sent by this queue.
4.755895
4.741902
1.002951
return self.store.findUnique( _QueuedMessage, AND(_QueuedMessage.senderUsername == sender.localpart, _QueuedMessage.senderDomain == sender.domain, _QueuedMessage.messageID == messageID), default=None)
def _messageFromSender(self, sender, messageID)
Locate a previously queued message by a given sender and messageID.
5.584015
4.897361
1.140209
if self.store.findFirst( LoginMethod, AND(LoginMethod.localpart == sender.localpart, LoginMethod.domain == sender.domain, LoginMethod.internal == True)) is None: raise BadSender(sender.localpart + u'@' + sender.domain, ...
def _verifySender(self, sender)
Verify that this sender is valid.
4.83153
4.476507
1.079308
self.messageCounter += 1 _QueuedMessage.create(store=self.store, sender=sender, target=target, value=value, messageID=self.messageCounter, conseq...
def queueMessage(self, sender, target, value, consequence=None)
Queue a persistent outgoing message. @param sender: The a description of the shared item that is the sender of the message. @type sender: L{xmantissa.sharing.Identifier} @param target: The a description of the shared item that is the target of the message. @type target:...
4.747343
5.908049
0.803538
delay = None router = self.siteRouter for qmsg in self.store.query(_QueuedMessage, sort=_QueuedMessage.storeID.ascending): try: self._verifySender(qmsg.sender) except: self.routeAnswer(qmsg.send...
def run(self)
Attmept to deliver the first outgoing L{QueuedMessage}; return a time to reschedule if there are still more retries or outgoing messages to send.
4.925415
4.451203
1.106536
objects[name] = getattr(proto, self.attr)
def fromBox(self, name, strings, objects, proto)
Retreive an attribute from the C{proto} parameter.
14.514969
9.723659
1.492748
messageBox = cmdObj.makeArguments(args, self) messageBox[COMMAND] = cmdObj.commandName messageData = messageBox.serialize() self.queue.queueMessage(self.sender, self.target, Value(AMP_MESSAGE_TYPE, messageData), con...
def messageRemote(self, cmdObj, consequence=None, **args)
Send a message to the peer identified by the target, via the given L{Command} object and arguments. @param cmdObj: a L{twisted.protocols.amp.Command}, whose serialized form will be the message. @param consequence: an L{IDeliveryConsequence} provider which will handle the result...
11.645467
10.787657
1.079518
thunk = super(_AMPExposer, self).expose(commandObject.commandName) def thunkplus(function): result = thunk(function) result.command = commandObject return result return thunkplus
def expose(self, commandObject)
Declare a method as being related to the given command object. @param commandObject: a L{Command} subclass.
7.593752
9.415296
0.806534
method = super(_AMPExposer, self).get(instance, commandName) return method
def responderForName(self, instance, commandName)
When resolving a command to a method from the wire, the information available is the command's name; look up a command. @param instance: an instance of a class who has methods exposed via this exposer's L{_AMPExposer.expose} method. @param commandName: the C{commandName} attribute of a...
30.212337
11.50101
2.626929
thunk = super(_AMPErrorExposer, self).expose( (commandObject.commandName, commandObject.errors.get(exceptionType))) def thunkplus(function): result = thunk(function) result.command = commandObject result.exception = exceptionType ...
def expose(self, commandObject, exceptionType)
Expose a function for processing a given AMP error.
6.947195
5.363688
1.295227
return super(_AMPErrorExposer, self).get(instance, (commandName, errorName))
def errbackForName(self, instance, commandName, errorName)
Retrieve an errback - a callable object that accepts a L{Failure} as an argument - that is exposed on the given instance, given an AMP commandName and a name in that command's error mapping.
18.020699
11.983852
1.503748
inputBoxes = parseString(messageData) if not len(inputBoxes) == 1: raise MalformedMessage() [inputBox] = inputBoxes return inputBox
def _boxFromData(self, messageData)
A box. @param messageData: a serialized AMP box representing either a message or an error. @type messageData: L{str} @raise MalformedMessage: if the C{messageData} parameter does not parse to exactly one AMP box.
6.282983
5.128735
1.225055
if value.type != AMP_MESSAGE_TYPE: raise UnknownMessageType() inputBox = self._boxFromData(value.data) thunk = commandMethod.responderForName(self, inputBox[COMMAND]) placeholder = _ProtocolPlaceholder(sender, target) arguments = thunk.command.parseArguments(...
def messageReceived(self, value, sender, target)
An AMP-formatted message was received. Dispatch to the appropriate command responder, i.e. a method on this object exposed with L{commandMethod.expose}. @see IMessageReceiver.messageReceived
7.903121
6.937131
1.139249
if value.type != AMP_ANSWER_TYPE: raise UnknownMessageType() commandName = self._boxFromData(originalValue.data)[COMMAND] rawArgs = self._boxFromData(value.data) placeholder = _ProtocolPlaceholder(originalSender, originalTarget) if ERROR in rawArgs: ...
def answerReceived(self, value, originalValue, originalSender, originalTarget)
An answer was received. Dispatch to the appropriate answer responder, i.e. a method on this object exposed with L{answerMethod.expose}. @see IDeliveryConsequence.answerReceived
8.837942
8.343311
1.059285
''' Wrapper around requests.get that shorten caller url and takes care of errors ''' # Avoid dangerous default function argument `{}` payload = payload or {} # Build the request and return json response return requests.get( '{}/{}/{}'.format( s...
def _get(self, resource, payload=None)
Wrapper around requests.get that shorten caller url and takes care of errors
16.846972
8.675496
1.941903
''' Wrapper around requests.put that shorten caller url and takes care of errors ''' # Avoid dangerous default function argument `{}` payload = payload or {} # Build the request and return json response return requests.put( '{}/{}/{}'.format( s...
def _put(self, resource, payload=None)
Wrapper around requests.put that shorten caller url and takes care of errors
17.789001
9.065648
1.962243
query = "SELECT name FROM sqlite_master WHERE type='table'" cursor = self.connection.execute(query) results = cursor.fetchall() return [result_tuple[0] for result_tuple in results]
def table_names(self)
Returns names of all tables in the database
2.824373
2.462406
1.146997
for table_name in self.table_names(): self.execute_sql("DROP TABLE %s" % table_name) self.connection.commit()
def drop_all_tables(self)
Drop all tables in the database
3.067507
3.08298
0.994981
logger.info("Running sqlite query: \"%s\"", sql) self.connection.execute(sql) if commit: self.connection.commit()
def execute_sql(self, sql, commit=False)
Log and then execute a SQL query
4.420247
4.603418
0.96021
query = "SELECT version FROM %s" % METADATA_TABLE_NAME cursor = self.connection.execute(query) version = cursor.fetchone() if not version: return 0 else: return int(version[0])
def version(self)
What's the version of this database? Found in metadata attached by datacache when creating this database.
3.30528
2.767685
1.19424
require_integer(version, "version") create_metadata_sql = \ "CREATE TABLE %s (version INT)" % METADATA_TABLE_NAME self.execute_sql(create_metadata_sql) insert_version_sql = \ "INSERT INTO %s VALUES (%s)" % (METADATA_TABLE_NAME, version) self.execu...
def _finalize_database(self, version)
Create metadata table for database with version number. Parameters ---------- version : int Tag created database with user-specified version number
3.036985
3.118735
0.973787
require_string(table_name, "table name") require_iterable_of(column_types, tuple, name="rows") if primary is not None: require_string(primary, "primary") require_iterable_of(nullable, str, name="nullable") column_decls = [] for column_name, column_ty...
def _create_table(self, table_name, column_types, primary=None, nullable=())
Creates a sqlite3 table from the given metadata. Parameters ---------- column_types : list of (str, str) pairs First element of each tuple is the column name, second element is the sqlite3 type primary : str, optional Which column is the primary key nu...
2.11529
2.398616
0.88188
for table in tables: self._create_table( table_name=table.name, column_types=table.column_types, primary=table.primary_key, nullable=table.nullable) self._fill_table(table.name, table.rows) self._create_...
def create(self, tables, version)
Do the actual work of creating the database, filling its tables with values, creating indices, and setting the datacache version metadata. Parameters ---------- tables : list List of datacache.DatabaseTable objects version : int
3.063945
3.546649
0.863899
logger.info( "Creating index on %s (%s)", table_name, ", ".join(index_columns)) index_name = "%s_index_%s" % ( table_name, "_".join(index_columns)) self.connection.execute( "CREATE INDEX IF NOT EXISTS %s ON %s (%s)...
def _create_index(self, table_name, index_columns)
Creates an index over multiple columns of a given table. Parameters ---------- table_name : str index_columns : iterable of str Which columns should be indexed
2.10039
2.192188
0.958125
require_string(table_name, "table_name") require_iterable_of(indices, (tuple, list)) for index_column_set in indices: self._create_index(table_name, index_column_set)
def _create_indices(self, table_name, indices)
Create multiple indices (each over multiple columns) on a given table. Parameters ---------- table_name : str indices : iterable of tuples Multiple groups of columns, each of which should be indexed.
3.9579
4.668478
0.847792
res = IResource(model, None) if res is None: frag = INavigableFragment(model) fragmentName = getattr(frag, 'fragmentName', None) if fragmentName is not None: fragDocFactory = self._getDocFactory(fragmentName) if fragDocFactory ...
def wrapModel(self, model)
Converts application-provided model objects to L{IResource} providers.
5.860869
5.02636
1.166027
if self.fragment is not None: # There are still a bunch of bogus subclasses of this class, which # are used in a variety of distasteful ways. 'fragment' *should* # always be set to something that isn't None, but there's no way to # make sure that it will...
def locateChild(self, ctx, segments)
Attempt to locate the child via the '.fragment' attribute, then fall back to normal locateChild behavior.
10.345484
9.686118
1.068073
request = IRequest(context) webViewer = IWebViewer(self.store, None) childAndSegments = self.siteProduceResource(request, segments, webViewer) if childAndSegments is not None: return childAndSegments return NotFound
def locateChild(self, context, segments)
Return a statically defined child or a child defined by a site root plugin or an avatar from guard.
9.151263
8.256845
1.108325
# rootChild_* is not the same as child_, because its signature is # different. Maybe this should be done some other way. shortcut = getattr(self, 'rootChild_' + segments[0], None) if shortcut: res = shortcut(req, webViewer) if res is not None: ...
def siteProduceResource(self, req, segments, webViewer)
Retrieve a child resource and segments from rootChild_ methods on this object and SiteRootPlugins. @return: a 2-tuple of (resource, segments), suitable for return from locateChild. @param req: an L{IRequest} provider. @param segments: a tuple of L{str}s, the segments from the ...
4.646973
3.86539
1.2022
if interface is IResource: siteStore = self.store.parent if self.store.parent is None: siteStore = self.store return VirtualHostWrapper( siteStore, IWebViewer(self.store), self) return self
def indirect(self, interface)
Create a L{VirtualHostWrapper} so it can have the first chance to handle web requests.
8.172375
5.854919
1.395813
hostname = hostname.split(":")[0] for domain in getDomainNames(self.siteStore): if hostname.endswith("." + domain): username = hostname[:-len(domain) - 1] if username != "www": return username, domain return None
def subdomain(self, hostname)
Determine of which known domain the given hostname is a subdomain. @return: A two-tuple giving the subdomain part and the domain part or C{None} if the domain is not a subdomain of any known domain.
4.981698
5.391713
0.923954
request = IRequest(context) hostname = request.getHeader('host') info = self.subdomain(hostname) if info is not None: username, domain = info index = UserIndexPage(IRealm(self.siteStore), self.webViewer) reso...
def locateChild(self, context, segments)
Delegate dispatch to a sharing resource if the request is for a user subdomain, otherwise fall back to the wrapped resource's C{locateChild} implementation.
7.10397
5.904011
1.203245
if fallback is None: fallback = IWebTranslator(store, None) if fallback is None: warnings.warn( "No IWebTranslator plugin when creating Scrolltable - broken " "configuration, now deprecated! Try passing webTranslator " "keyword argume...
def _webTranslator(store, fallback)
Discover a web translator based on an Axiom store and a specified default. Prefer the specified default. This is an implementation detail of various initializers in this module which require an L{IWebTranslator} provider. Some of those initializers did not previously require a webTranslator, so this f...
12.548802
12.154908
1.032406
csc = self.currentSortColumn newSortColumn = self.columns[columnName] if newSortColumn is None: raise Unsortable('column %r has no sort attribute' % (columnName,)) if csc is newSortColumn: self.isAscending = not self.isAscending else: ...
def resort(self, columnName)
Re-sort the table. @param columnName: the name of the column to sort by. This is a string because it is passed from the browser.
3.857849
3.881104
0.994008
if self.baseConstraint is not None: if constraint is not None: constraint = AND(self.baseConstraint, constraint) else: constraint = self.baseConstraint # build the sort currentSortAttribute = self.currentSortColumn.sortAttribute() ...
def inequalityQuery(self, constraint, count, isAscending)
Perform a query to obtain some rows from the table represented by this model, at the behest of a networked client. @param constraint: an additional constraint to apply to the query. @type constraint: L{axiom.iaxiom.IComparison}. @param count: the maximum number of rows to retur...
3.673387
3.688049
0.996024
if value is None: query = self.inequalityQuery(None, count, True) else: pyvalue = self._toComparableValue(value) currentSortAttribute = self.currentSortColumn.sortAttribute() query = self.inequalityQuery(currentSortAttribute >= pyvalue, count, Tru...
def rowsAfterValue(self, value, count)
Retrieve some rows at or after a given sort-column value. @param value: Starting value in the index for the current sort column at which to start returning results. Rows with a column value for the current sort column which is greater than or equal to this value will be returned. ...
6.610153
7.072228
0.934663
webID = rowObject['__id__'] return self.rowsAfterItem( self.webTranslator.fromWebID(webID), count)
def rowsAfterRow(self, rowObject, count)
Wrapper around L{rowsAfterItem} which accepts the web ID for a item instead of the item itself. @param rowObject: a dictionary mapping strings to column values, sent from the client. One of those column values must be C{__id__} to uniquely identify a row. @param count: an inte...
13.236567
7.117511
1.859719
webID = rowObject['__id__'] return self.rowsBeforeItem( self.webTranslator.fromWebID(webID), count)
def rowsBeforeRow(self, rowObject, count)
Wrapper around L{rowsBeforeItem} which accepts the web ID for a item instead of the item itself. @param rowObject: a dictionary mapping strings to column values, sent from the client. One of those column values must be C{__id__} to uniquely identify a row. @param count: an int...
13.007614
7.160349
1.816617
if hasattr(self.currentSortColumn, 'toComparableValue'): return self.currentSortColumn.toComparableValue(value) # Retrieve the location of the class's definition so that we can alert # the user as to where they need to insert their implementation. classDef = self.cur...
def _toComparableValue(self, value)
Trivial wrapper which takes into account the possibility that our sort column might not have defined the C{toComparableValue} method. This can probably serve as a good generic template for some infrastructure to deal with arbitrarily-potentially-missing methods from certain versions of ...
5.435354
4.786221
1.135625
if value is None: query = self.inequalityQuery(None, count, False) else: pyvalue = self._toComparableValue(value) currentSortAttribute = self.currentSortColumn.sortAttribute() query = self.inequalityQuery( currentSortAttribute < py...
def rowsBeforeValue(self, value, count)
Retrieve display data for rows with sort-column values less than the given value. @type value: Some type compatible with the current sort column. @param value: Starting value in the index for the current sort column at which to start returning results. Rows with a column value for the ...
6.978337
7.133895
0.978195
currentSortAttribute = self.currentSortColumn.sortAttribute() value = currentSortAttribute.__get__(item, type(item)) firstQuery = self.inequalityQuery( AND(currentSortAttribute == value, self.itemType.storeID < item.storeID), count, False) ...
def rowsBeforeItem(self, item, count)
The inverse of rowsAfterItem. @param item: then L{Item} to request rows before. @type item: this L{InequalityModel}'s L{itemType} attribute. @param count: The maximum number of rows to return. @type count: L{int} @return: A list of row data, ordered by the current sort column,...
5.219608
4.656239
1.120992
return self.constructRows(self.performQuery(rangeBegin, rangeEnd))
def requestRowRange(self, rangeBegin, rangeEnd)
Retrieve display data for the given range of rows. @type rangeBegin: C{int} @param rangeBegin: The index of the first row to retrieve. @type rangeEnd: C{int} @param rangeEnd: The index of the last row to retrieve. @return: A C{list} of C{dict}s giving row data.
12.992371
18.896473
0.687555
coltypes = {} for (colname, column) in self.columns.iteritems(): sortable = column.sortAttribute() is not None coltype = column.getType() if coltype is not None: coltype = unicode(coltype, 'ascii') coltypes[colname] = (coltype, sor...
def getTableMetadata(self)
Retrieve a description of the various properties of this scrolltable. @return: A sequence containing 5 elements. They are, in order, a list of the names of the columns present, a mapping of column names to two-tuples of their type and a boolean indicating their sortability, the total n...
4.811917
4.239224
1.135094
rows = [] for item in items: row = dict((colname, col.extractValue(self, item)) for (colname, col) in self.columns.iteritems()) link = self.linkToItem(item) if link is not None: row[u'__id__'] = link rows.app...
def constructRows(self, items)
Build row objects that are serializable using Athena for sending to the client. @param items: an iterable of objects compatible with my columns' C{extractValue} methods. @return: a list of dictionaries, where each dictionary has a string key for each column name in my list of c...
3.508404
3.318872
1.057107
columnList = [] for columnName in self.columnNames: column = self.columns[columnName] type = column.getType() if type is None: type = 'text' columnList.append( {u'name': columnName, u'type': type.de...
def _getColumnList(self)
Get a list of serializable objects that describe the interesting columns on our item type. Columns which report having no type will be treated as having the type I{text}. @rtype: C{list} of C{dict}
3.296499
3.123367
1.055432
ic = IColumn(self.currentSortColumn) return [ic.attributeID.decode('ascii'), self._getColumnList(), self.isAscending]
def getInitialArguments(self)
Return the constructor arguments required for the JavaScript client class, Mantissa.ScrollTable.ScrollTable. @return: a 3-tuple of:: - The unicode attribute ID of my current sort column - A list of dictionaries with 'name' and 'type' keys which are strings describing th...
29.098885
12.793602
2.274487
fovobj = fields.getKeplerFov(campaign) ch, col, row = fovobj.getChannelColRow(ra, dec) print("Position in C{}: channel {}, col {:.0f}, row {:.0f}.".format(campaign, int(ch), col, row))
def printChannelColRow(campaign, ra, dec)
Prints the channel, col, row for a given campaign and coordinate.
7.502569
6.979126
1.075001
# Temporary disable the logger to avoid the preliminary field warnings logger.disabled = True campaigns_visible = [] for c in fields.getFieldNumbers(): fovobj = fields.getKeplerFov(c) if onSiliconCheck(ra, dec, fovobj): campaigns_visible.append(c) # Re-enable the log...
def findCampaigns(ra, dec)
Returns a list of the campaigns that cover a given position. Parameters ---------- ra, dec : float, float Position in decimal degrees (J2000). Returns ------- campaigns : list of int A list of the campaigns that cover the given position.
9.097627
9.351644
0.972837
# Is AstroPy (optional dependency) installed? try: from astropy.coordinates import SkyCoord from astropy.coordinates.name_resolve import NameResolveError from astropy.utils.data import conf conf.remote_timeout = 90 except ImportError: print('Error: AstroPy needs ...
def findCampaignsByName(target)
Returns a list of the campaigns that cover a given target. Parameters ---------- target : str Name of the celestial object. Returns ------- campaigns : list of int A list of the campaigns that cover the given target name. ra, dec : float, float Resolved coordinates...
3.825314
3.512936
1.088922
parser = argparse.ArgumentParser( description="Check if a celestial coordinate is " "(or was) observable by any past or future " "observing campaign of NASA's K2 mission.") parser.add_argument('ra', nargs=1, type=float, ...
def K2findCampaigns_main(args=None)
Exposes K2findCampaigns to the command line.
3.989422
3.955569
1.008558
parser = argparse.ArgumentParser( description="Check if a target is " "(or was) observable by any past or future " "observing campaign of NASA's K2 mission.") parser.add_argument('name', nargs=1, type=str, ...
def K2findCampaigns_byname_main(args=None)
Exposes K2findCampaigns to the command line.
4.827363
4.798734
1.005966
parser = argparse.ArgumentParser( description="Check which objects listed in a CSV table " "are (or were) observable by NASA's K2 mission.") parser.add_argument('input_filename', nargs=1, type=str, help="Path to a comma-separated t...
def K2findCampaigns_csv_main(args=None)
Exposes K2findCampaigns-csv to the command line.
3.034568
3.036406
0.999395
do_not_mock = _to_list(do_not_mock) def try_import(module_name, *args, **kwargs): try: return _builtins_import(module_name, *args, **kwargs) except: # intentionally catch all exceptions if any((_match(module_name, prefix) for prefix in do_not_mock)): ...
def mock_import(do_not_mock=None, **mock_kwargs)
Mocks import statements by ignoring ImportErrors and replacing the missing module with a Mock. :param str|unicode|list[str|unicode] do_not_mock: names of modules that should exists, and an ImportError could be raised for. :param mock_kwargs: kwargs for MagicMock object. :return: patch object
4.714738
5.167712
0.912345
if url.startswith('/'): url = self.endpoint + url attrs = { "headers": {"Authorization": "Bearer " + self.api_token}, "params": params if params is not None else {}, "timeout": self.timeout, } method = method.upper() if dat...
def request(self, url, params=None, data=None, method='GET')
Perform an HTTP request and return the response body as a decoded JSON value :param str url: the URL to make the request of. If ``url`` begins with a forward slash, :attr:`endpoint` is prepended to it; otherwise, ``url`` is treated as an absolute URL. :param dict params...
2.299911
2.199167
1.04581
if self.last_response is None: return None else: return {k:v for k,v in iteritems(self.last_response.headers) if k.lower().startswith('ratelimit')}
def last_rate_limit(self)
A `dict` of the rate limit information returned in the most recent response, or `None` if no requests have been made yet. The `dict` consists of all headers whose names begin with ``"RateLimit"`` (case insensitive). The DigitalOcean API specifies the following rate limit headers: ...
3.832951
3.806814
1.006866
if params is None: params = {} if self.per_page is not None and "per_page" not in params: params = dict(params, per_page=self.per_page) page = self.request(url, params=params) while True: try: objects = page[key] ex...
def paginate(self, url, key, params=None)
Fetch a sequence of paginated resources from the API endpoint. The initial request to ``url`` and all subsequent requests must respond with a JSON object; the field specified by ``key`` must be a list, whose elements will be yielded, and the next request will be made to the URL in the `...
2.61264
2.635256
0.991418
r params = {} if tag_name is not None: params["tag_name"] = str(tag_name) return map(self._droplet, self.paginate('/v2/droplets', 'droplets', params=params))
def fetch_all_droplets(self, tag_name=None)
r""" Returns a generator that yields all of the droplets belonging to the account .. versionchanged:: 0.2.0 ``tag_name`` parameter added :param tag_name: if non-`None`, only droplets with the given tag are returned :type tag_name: string or `Tag` ...
4.719869
6.027239
0.78309
data = { "name": name, "image": image.id if isinstance(image, Image) else image, "size": str(size), "region": str(region), } if ssh_keys is not None: data["ssh_keys"] = [k._id if isinstance(k, SSHKey) else k ...
def create_droplet(self, name, image, size, region, ssh_keys=None, backups=None, ipv6=None, private_networking=None, user_data=None, **kwargs)
Create a new droplet. All fields other than ``name``, ``image``, ``size``, and ``region`` are optional and will be omitted from the API request if not specified. The returned `Droplet` object will represent the droplet at the moment of creation; the actual droplet may not be active yet...
1.814026
1.913885
0.947824
r data = { "names": names, "image": image.id if isinstance(image, Image) else image, "size": str(size), "region": str(region), } if ssh_keys is not None: data["ssh_keys"] = [k._id if isinstance(k, SSHKey) else k ...
def create_multiple_droplets(self, names, image, size, region, ssh_keys=None, backups=None, ipv6=None, private_networking=None, user_data=None, **kwargs)
r""" Create multiple new droplets at once with the same image, size, etc., differing only in name. All fields other than ``names``, ``image``, ``size``, and ``region`` are optional and will be omitted from the API request if not specified. The returned `Droplet` objects will re...
2.088118
2.324976
0.898124
r for hood in self.paginate('/v2/reports/droplet_neighbors', 'neighbors'): yield list(map(self._droplet, hood))
def fetch_all_droplet_neighbors(self)
r""" Returns a generator of all sets of multiple droplets that are running on the same physical hardware :rtype: generator of lists of `Droplet`\ s :raises DOAPIError: if the API endpoint replies with an error
18.252623
22.062639
0.827309