INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Do not warn on external images.
def _warn_node(self, msg, *args, **kwargs): """Do not warn on external images.""" if not msg.startswith('nonlocal image URI found:'): _warn_node_old(self, msg, *args, **kwargs)
Connect receivers to signals.
def connect_receivers(): """Connect receivers to signals.""" request_created.connect(send_email_validation) request_confirmed.connect(send_confirmed_notifications) request_rejected.connect(send_reject_notification) # Order is important: request_accepted.connect(create_secret_link) request_ac...
Receiver for request - accepted signal.
def create_secret_link(request, message=None, expires_at=None): """Receiver for request-accepted signal.""" pid, record = get_record(request.recid) if not record: raise RecordNotFound(request.recid) description = render_template( "zenodo_accessrequests/link_description.tpl", req...
Receiver for request - accepted signal to send email notification.
def send_accept_notification(request, message=None, expires_at=None): """Receiver for request-accepted signal to send email notification.""" pid, record = get_record(request.recid) _send_notification( request.sender_email, _("Access request accepted"), "zenodo_accessrequests/emails/a...
Receiver for request - confirmed signal to send email notification.
def send_confirmed_notifications(request): """Receiver for request-confirmed signal to send email notification.""" pid, record = get_record(request.recid) if record is None: current_app.logger.error("Cannot retrieve record %s. Emails not sent" % request.recid) ...
Receiver for request - created signal to send email notification.
def send_email_validation(request): """Receiver for request-created signal to send email notification.""" token = EmailConfirmationSerializer().create_token( request.id, dict(email=request.sender_email) ) pid, record = get_record(request.recid) _send_notification( request.sender_ema...
Receiver for request - rejected signal to send email notification.
def send_reject_notification(request, message=None): """Receiver for request-rejected signal to send email notification.""" pid, record = get_record(request.recid) _send_notification( request.sender_email, _("Access request rejected"), "zenodo_accessrequests/emails/rejected.tpl", ...
Render a template and send as email.
def _send_notification(to, subject, template, **ctx): """Render a template and send as email.""" msg = Message( subject, sender=current_app.config.get('SUPPORT_EMAIL'), recipients=[to] ) msg.body = render_template(template, **ctx) send_email.delay(msg.__dict__)
Create a new secret link.
def create(cls, title, owner, extra_data, description="", expires_at=None): """Create a new secret link.""" if isinstance(expires_at, date): expires_at = datetime.combine(expires_at, datetime.min.time()) with db.session.begin_nested(): obj = cls( owner=ow...
Validate a secret link token.
def validate_token(cls, token, expected_data): """Validate a secret link token. Only queries the database if token is valid to determine that the token has not been revoked. """ data = SecretLinkFactory.validate_token( token, expected_data=expected_data ) ...
Load token data stored in token ( ignores expiry date of tokens ).
def extra_data(self): """Load token data stored in token (ignores expiry date of tokens).""" if self.token: return SecretLinkFactory.load_token(self.token, force=True)["data"] return None
Get absolute for secret link ( using https scheme ).
def get_absolute_url(self, endpoint): """Get absolute for secret link (using https scheme). The endpoint is passed to ``url_for`` with ``token`` and ``extra_data`` as keyword arguments. E.g.:: >>> link.extra_data dict(recid=1) >>> link.get_absolute_url('reco...
Revoken a secret link.
def revoke(self): """Revoken a secret link.""" if self.revoked_at is None: with db.session.begin_nested(): self.revoked_at = datetime.utcnow() link_revoked.send(self) return True return False
Create a new access request.
def create(cls, recid=None, receiver=None, sender_full_name=None, sender_email=None, justification=None, sender=None): """Create a new access request. :param recid: Record id (required). :param receiver: User object of receiver (required). :param sender_full_name: Full na...
Get access request for a specific receiver.
def get_by_receiver(cls, request_id, user): """Get access request for a specific receiver.""" return cls.query.filter_by( id=request_id, receiver_user_id=user.id ).first()
Confirm that senders email is valid.
def confirm_email(self): """Confirm that senders email is valid.""" with db.session.begin_nested(): if self.status != RequestStatus.EMAIL_VALIDATION: raise InvalidRequestStateError(RequestStatus.EMAIL_VALIDATION) self.status = RequestStatus.PENDING reques...
Accept request.
def accept(self, message=None, expires_at=None): """Accept request.""" with db.session.begin_nested(): if self.status != RequestStatus.PENDING: raise InvalidRequestStateError(RequestStatus.PENDING) self.status = RequestStatus.ACCEPTED request_accepted.send...
Reject request.
def reject(self, message=None): """Reject request.""" with db.session.begin_nested(): if self.status != RequestStatus.PENDING: raise InvalidRequestStateError(RequestStatus.PENDING) self.status = RequestStatus.REJECTED request_rejected.send(self, message=me...
Create a secret link from request.
def create_secret_link(self, title, description=None, expires_at=None): """Create a secret link from request.""" self.link = SecretLink.create( title, self.receiver, extra_data=dict(recid=self.recid), description=description, expires_at=expires...
Given required properties from a NistBeaconValue compute the SHA512Hash object.
def get_hash( cls, version: str, frequency: int, timestamp: int, seed_value: str, prev_output: str, status_code: str, ) -> SHA512Hash: """ Given required properties from a NistBeaconValue, compute the SHA512H...
Verify a given NIST message hash and signature for a beacon value.
def verify( cls, timestamp: int, message_hash: SHA512Hash, signature: bytes, ) -> bool: """ Verify a given NIST message hash and signature for a beacon value. :param timestamp: The timestamp of the record being verified. :param message...
Template filter to check if a record is embargoed.
def is_embargoed(record): """Template filter to check if a record is embargoed.""" return record.get('access_right') == 'embargoed' and \ record.get('embargo_date') and \ record.get('embargo_date') > datetime.utcnow().date()
Create an access request.
def access_request(pid, record, template, **kwargs): """Create an access request.""" recid = int(pid.pid_value) datastore = LocalProxy( lambda: current_app.extensions['security'].datastore) # Record must be in restricted access mode. if record.get('access_right') != 'restricted' or \ ...
Confirm email address.
def confirm(pid, record, template, **kwargs): """Confirm email address.""" recid = int(pid.pid_value) token = request.view_args['token'] # Validate token data = EmailConfirmationSerializer.compat_validate_token(token) if data is None: flash(_("Invalid confirmation link."), category='da...
Creates a generic endpoint connection that doesn t finish
def _get_endpoint(self): """ Creates a generic endpoint connection that doesn't finish """ return SSHCommandClientEndpoint.newConnection( reactor, b'/bin/cat', self.username, self.hostname, port=self.port, keys=self.keys, password=self.password, knownHosts = s...
Get reverse direction of ordering.
def reverse(self, col): """Get reverse direction of ordering.""" if col in self.options: if self.is_selected(col): return col if not self.asc else '-{0}'.format(col) else: return col return None
Get direction ( ascending/ descending ) of ordering.
def dir(self, col, asc='asc', desc='desc'): """Get direction (ascending/descending) of ordering.""" if col == self._selected and self.asc is not None: return asc if self.asc else desc else: return None
Get column which is being order by.
def selected(self): """Get column which is being order by.""" if self._selected: return self._selected if self.asc else \ "-{0}".format(self._selected) return None
Get query with correct ordering.
def items(self): """Get query with correct ordering.""" if self.asc is not None: if self._selected and self.asc: return self.query.order_by(self._selected) elif self._selected and not self.asc: return self.query.order_by(desc(self._selected)) ...
Open the file referenced in this object and scrape the version.
def get_version(self) -> str: """ Open the file referenced in this object, and scrape the version. :return: The version as a string, an empty string if there is no match to the magic_line, or any file exception messages encountered. """ try: ...
Set the version for this given file.
def set_version(self, new_version: str): """ Set the version for this given file. :param new_version: The new version string to set. """ try: f = open(self.file_path, 'r') lines = f.readlines() f.close() except Exception as e: ...
Load test data fixture.
def records(): """Load test data fixture.""" import uuid from invenio_records.api import Record from invenio_pidstore.models import PersistentIdentifier, PIDStatus create_test_user() indexer = RecordIndexer() # Record 1 - Live record with db.session.begin_nested(): rec_uuid = ...
Configure SSH client options
def _init_ssh(self): """ Configure SSH client options """ self.ssh_host = self.config.get('ssh_host', self.hostname) self.known_hosts = self.config.get('ssh_knownhosts_file', self.tensor.config.get('ssh_knownhosts_file', None)) self.ssh_keyfile = self.config.get('s...
Starts the timer for this source
def startTimer(self): """Starts the timer for this source""" self.td = self.t.start(self.inter) if self.use_ssh and self.ssh_connector: self.ssh_client.connect()
Called for every timer tick. Calls self. get which can be a deferred and passes that result back to the queueBack method Returns a deferred
def tick(self): """Called for every timer tick. Calls self.get which can be a deferred and passes that result back to the queueBack method Returns a deferred""" if self.sync: if self.running: defer.returnValue(None) self.running = True ...
Creates an Event object from the Source configuration
def createEvent(self, state, description, metric, prefix=None, hostname=None, aggregation=None, evtime=None): """Creates an Event object from the Source configuration""" if prefix: service_name = self.service + "." + prefix else: service_name = self.service ...
Creates an Event object from the Source configuration
def createLog(self, type, data, evtime=None, hostname=None): """Creates an Event object from the Source configuration""" return Event(None, type, data, 0, self.ttl, hostname=hostname or self.hostname, evtime=evtime, tags=self.tags, type='log' )
List pending access requests and shared links.
def index(): """List pending access requests and shared links.""" query = request.args.get('query', '') order = request.args.get('sort', '-created') try: page = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', 20)) except (TypeError, ValueError): a...
Accept/ reject access request.
def accessrequest(request_id): """Accept/reject access request.""" r = AccessRequest.get_by_receiver(request_id, current_user) if not r or r.status != RequestStatus.PENDING: abort(404) form = ApprovalForm(request.form) if form.validate_on_submit(): if form.accept.data: ...
Create a TCP connection to Riemann with automatic reconnection
def createClient(self): """Create a TCP connection to Riemann with automatic reconnection """ server = self.config.get('server', 'localhost') port = self.config.get('port', 5555) failover = self.config.get('failover', False) self.factory = riemann.RiemannClientFactory(s...
Stop this client.
def stop(self): """Stop this client. """ self.t.stop() self.factory.stopTrying() self.connector.disconnect()
Clock tick called every self. inter
def tick(self): """Clock tick called every self.inter """ if self.factory.proto: # Check backpressure if (self.pressure < 0) or (self.factory.proto.pressure <= self.pressure): self.emptyQueue() elif self.expire: # Check queue age and ex...
Remove all or self. queueDepth events from the queue
def emptyQueue(self): """Remove all or self.queueDepth events from the queue """ if self.events: if self.queueDepth and (len(self.events) > self.queueDepth): # Remove maximum of self.queueDepth items from queue events = self.events[:self.queueDepth] ...
Receives a list of events and transmits them to Riemann
def eventsReceived(self, events): """Receives a list of events and transmits them to Riemann Arguments: events -- list of `tensor.objects.Event` """ # Make sure queue isn't oversized if (self.maxsize < 1) or (len(self.events) < self.maxsize): self.events.exte...
Create a UDP connection to Riemann
def createClient(self): """Create a UDP connection to Riemann""" server = self.config.get('server', '127.0.0.1') port = self.config.get('port', 5555) def connect(ip): self.protocol = riemann.RiemannUDP(ip, port) self.endpoint = reactor.listenUDP(0, self.protocol)...
Sets up HTTP connector and starts queue timer
def createClient(self): """Sets up HTTP connector and starts queue timer """ server = self.config.get('server', 'localhost') port = int(self.config.get('port', 9200)) self.client = elasticsearch.ElasticSearch(self.url, self.user, self.password, self.index) ...
Clock tick called every self. inter
def tick(self): """Clock tick called every self.inter """ if self.events: if self.queueDepth and (len(self.events) > self.queueDepth): # Remove maximum of self.queueDepth items from queue events = self.events[:self.queueDepth] self.even...
Adapts an Event object to a Riemann protobuf event Event
def encodeEvent(self, event): """Adapts an Event object to a Riemann protobuf event Event""" pbevent = proto_pb2.Event( time=int(event.time), state=event.state, service=event.service, host=event.hostname, description=event.description, ...
Encode a list of Tensor events with protobuf
def encodeMessage(self, events): """Encode a list of Tensor events with protobuf""" message = proto_pb2.Msg( events=[self.encodeEvent(e) for e in events if e._type=='riemann'] ) return message.SerializeToString()
Decode a protobuf message into a list of Tensor events
def decodeMessage(self, data): """Decode a protobuf message into a list of Tensor events""" message = proto_pb2.Msg() message.ParseFromString(data) return message
Send a Tensor Event to Riemann
def sendEvents(self, events): """Send a Tensor Event to Riemann""" self.pressure += 1 self.sendString(self.encodeMessage(events))
Generate preview for URL.
def generate(ctx, url, *args, **kwargs): """ Generate preview for URL. """ file_previews = ctx.obj['file_previews'] options = {} metadata = kwargs['metadata'] width = kwargs['width'] height = kwargs['height'] output_format = kwargs['format'] if metadata: options['metada...
Retreive preview results for ID.
def retrieve(ctx, preview_id, *args, **kwargs): """ Retreive preview results for ID. """ file_previews = ctx.obj['file_previews'] results = file_previews.retrieve(preview_id) click.echo(results)
If the client application has a refresh token it can use it to send a request for a new access token. To ask for a new access token the client application should send a POST request to https:// login. instance_name/ services/ oauth2/ token with the following query parameters: grant_type: Value must be refresh_token for...
def _refresh_access_token(self): """ If the client application has a refresh token, it can use it to send a request for a new access token. To ask for a new access token, the client application should send a POST request to https://login.instance_name/services/oauth2/token with the fol...
Send message dicts through r_q and throw explicit errors for pickle problems
def r_q_send(self, msg_dict): """Send message dicts through r_q, and throw explicit errors for pickle problems""" # Check whether msg_dict can be pickled... no_pickle_keys = self.invalid_dict_pickle_keys(msg_dict) if no_pickle_keys == []: self.r_q.put(msg_dict) ...
Return a list of keys that can t be pickled. Return [] if there are no pickling problems with the values associated with the keys. Return the list of keys if there are problems.
def invalid_dict_pickle_keys(self, msg_dict): """Return a list of keys that can't be pickled. Return [] if there are no pickling problems with the values associated with the keys. Return the list of keys, if there are problems.""" no_pickle_keys = list() for key, val in msg_di...
Loop through messages and execute tasks
def message_loop(self, t_q, r_q): """Loop through messages and execute tasks""" t_msg = {} while t_msg.get("state", "") != "__DIE__": try: t_msg = t_q.get(True, self.cycle_sleep) # Poll blocking self.task = t_msg.get("task", "") # __DIE__ has no task...
Return True if it s time to log
def log_time(self): """Return True if it's time to log""" if self.hot_loop and self.time_delta >= self.log_interval: return True return False
Build a log message and reset the stats
def log_message(self): """Build a log message and reset the stats""" time_delta = deepcopy(self.time_delta) total_work_time = self.worker_count * time_delta time_worked = sum(self.exec_times) pct_busy = time_worked / total_work_time * 100.0 min_task_time = min(self.exec_...
If not in a hot_loop call supervise () to start the tasks
def supervise(self): """If not in a hot_loop, call supervise() to start the tasks""" self.retval = set([]) stats = TaskMgrStats( worker_count=self.worker_count, log_interval=self.log_interval, hot_loop=self.hot_loop, ) hot_loop = self.hot_loop...
Respawn workers/ tasks upon crash
def respawn_dead_workers(self): """Respawn workers / tasks upon crash""" for w_id, p in self.workers.items(): if not p.is_alive(): # Queue the task for another worker, if required... if self.log_level >= 2: self.log.info("Worker w_id {0} di...
Return synchronous version of Monoprice interface: param port_url: serial port i. e./ dev/ ttyUSB0: return: synchronous implementation of Monoprice interface
def get_monoprice(port_url): """ Return synchronous version of Monoprice interface :param port_url: serial port, i.e. '/dev/ttyUSB0' :return: synchronous implementation of Monoprice interface """ lock = RLock() def synchronized(func): @wraps(func) def wrapper(*args, **kwarg...
Return asynchronous version of Monoprice interface: param port_url: serial port i. e./ dev/ ttyUSB0: return: asynchronous implementation of Monoprice interface
def get_async_monoprice(port_url, loop): """ Return asynchronous version of Monoprice interface :param port_url: serial port, i.e. '/dev/ttyUSB0' :return: asynchronous implementation of Monoprice interface """ lock = asyncio.Lock() def locked_coro(coro): @asyncio.coroutine ...
Comptaibility layer for old: class: SASLInterface implementations.
def from_reply(cls, state): """ Comptaibility layer for old :class:`SASLInterface` implementations. Accepts the follwing set of :class:`SASLState` or strings and maps the strings to :class:`SASLState` elements as follows: ``"challenge"`` :member:`SASLState...
Initiate the SASL handshake and advertise the use of the given mechanism. If payload is not: data: None it will be base64 encoded and sent as initial client response along with the <auth/ > element.
def initiate(self, mechanism, payload=None): """ Initiate the SASL handshake and advertise the use of the given `mechanism`. If `payload` is not :data:`None`, it will be base64 encoded and sent as initial client response along with the ``<auth />`` element. Return the ne...
Send a response to the previously received challenge with the given payload. The payload is encoded using base64 and transmitted to the server.
def response(self, payload): """ Send a response to the previously received challenge, with the given `payload`. The payload is encoded using base64 and transmitted to the server. Return the next state of the state machine as tuple (see :class:`SASLStateMachine` for deta...
Abort an initiated SASL authentication process. The expected result state is failure.
def abort(self): """ Abort an initiated SASL authentication process. The expected result state is ``failure``. """ if self._state == SASLState.INITIAL: raise RuntimeError("SASL authentication hasn't started yet") if self._state == SASLState.SUCCESS_SIMULATE_C...
Perform the stringprep mapping step of SASLprep. Operates in - place on a list of unicode characters provided in chars.
def _saslprep_do_mapping(chars): """ Perform the stringprep mapping step of SASLprep. Operates in-place on a list of unicode characters provided in `chars`. """ i = 0 while i < len(chars): c = chars[i] if stringprep.in_table_c12(c): chars[i] = "\u0020" elif st...
Implement the trace profile specified in: rfc: 4505.
def trace(string): """ Implement the ``trace`` profile specified in :rfc:`4505`. """ check_prohibited_output( string, ( stringprep.in_table_c21, stringprep.in_table_c22, stringprep.in_table_c3, stringprep.in_table_c4, stringpre...
Calculate the byte wise exclusive of of two: class: bytes objects of the same length.
def xor_bytes(a, b): """ Calculate the byte wise exclusive of of two :class:`bytes` objects of the same length. """ assert len(a) == len(b) return bytes(map(operator.xor, a, b))
Template tag that renders the footer information based on the authenticated user s permissions.
def admin_footer(parser, token): """ Template tag that renders the footer information based on the authenticated user's permissions. """ # split_contents() doesn't know how to split quoted strings. tag_name = token.split_contents() if len(tag_name) > 1: raise base.TemplateSyntaxErro...
Builds the parameters needed to present the user with a datatrans payment form.
def build_payment_parameters(amount: Money, client_ref: str) -> PaymentParameters: """ Builds the parameters needed to present the user with a datatrans payment form. :param amount: The amount and currency we want the user to pay :param client_ref: A unique reference for this payment :return: The p...
Builds the parameters needed to present the user with a datatrans form to register a credit card. Contrary to a payment form datatrans will not show an amount.
def build_register_credit_card_parameters(client_ref: str) -> PaymentParameters: """ Builds the parameters needed to present the user with a datatrans form to register a credit card. Contrary to a payment form, datatrans will not show an amount. :param client_ref: A unique reference for this alias capt...
Charges money using datatrans given a previously registered credit card alias.
def pay_with_alias(amount: Money, alias_registration_id: str, client_ref: str) -> Payment: """ Charges money using datatrans, given a previously registered credit card alias. :param amount: The amount and currency we want to charge :param alias_registration_id: The alias registration to use :param ...
Both alias registration and payments are received here. We can differentiate them by looking at the use - alias user - parameter ( and verifying the amount is o ).
def parse_notification_xml(xml: str) -> Union[AliasRegistration, Payment]: """" Both alias registration and payments are received here. We can differentiate them by looking at the use-alias user-parameter (and verifying the amount is o). """ body = fromstring(xml).find('body') transaction = bod...
Return short application version. For example: 1. 0. 0.
def short_version(version=None): """ Return short application version. For example: `1.0.0`. """ v = version or __version__ return '.'.join([str(x) for x in v[:3]])
Return full version nr inc. rc beta etc tags.
def get_version(version=None): """ Return full version nr, inc. rc, beta etc tags. For example: `2.0.0a1` :rtype: str """ v = version or __version__ if len(v) == 4: return '{0}{1}'.format(short_version(v), v[3]) return short_version(v)
Refunds ( partially or completely ) a previously authorized and settled payment.: param amount: The amount and currency we want to refund. Must be positive in the same currency as the original payment and not exceed the amount of the original payment.: param payment_id: The id of the payment to refund.: return: a Refun...
def refund(amount: Money, payment_id: str) -> Refund: """ Refunds (partially or completely) a previously authorized and settled payment. :param amount: The amount and currency we want to refund. Must be positive, in the same currency as the original payment, and not exceed the amount of the original pay...
Construct widget.
def _construct(self): '''Construct widget.''' self.setLayout(QtGui.QVBoxLayout()) self._headerLayout = QtGui.QHBoxLayout() self._locationWidget = QtGui.QComboBox() self._headerLayout.addWidget(self._locationWidget, stretch=1) self._upButton = QtGui.QToolButton() ...
Perform post - construction operations.
def _postConstruction(self): '''Perform post-construction operations.''' self.setWindowTitle('Filesystem Browser') self._filesystemWidget.sortByColumn(0, QtCore.Qt.AscendingOrder) # TODO: Remove once bookmarks widget implemented. self._bookmarksWidget.hide() self._accep...
Add keyboard shortcuts to navigate the filesystem.
def _configureShortcuts(self): '''Add keyboard shortcuts to navigate the filesystem.''' self._upShortcut = QtGui.QShortcut( QtGui.QKeySequence('Backspace'), self ) self._upShortcut.setAutoRepeat(False) self._upShortcut.activated.connect(self._onNavigateUpButtonClicked...
Handle activation of item in listing.
def _onActivateItem(self, index): '''Handle activation of item in listing.''' item = self._filesystemWidget.model().item(index) if not isinstance(item, riffle.model.File): self._acceptButton.setDisabled(True) self.setLocation(item.path, interactive=True)
Handle selection of item in listing.
def _onSelectItem(self, selection, previousSelection): '''Handle selection of item in listing.''' self._acceptButton.setEnabled(True) del self._selected[:] item = self._filesystemWidget.model().item(selection) self._selected.append(item.path)
Handle selection of path segment.
def _onNavigate(self, index): '''Handle selection of path segment.''' if index > 0: self.setLocation( self._locationWidget.itemData(index), interactive=True )
Return list of valid * path * segments.
def _segmentPath(self, path): '''Return list of valid *path* segments.''' parts = [] model = self._filesystemWidget.model() # Separate root path from remainder. remainder = path while True: if remainder == model.root.path: break ...
Set current location to * path *.
def setLocation(self, path, interactive=False): '''Set current location to *path*. *path* must be the same as root or under the root. .. note:: Comparisons are case-sensitive. If you set the root as 'D:/' then location can be set as 'D:/folder' *not* 'd:/folder'. ...
Set current location to * path *.
def _setLocation(self, path): '''Set current location to *path*. *path* must be the same as root or under the root. .. note:: Comparisons are case-sensitive. If you set the root as 'D:/' then location can be set as 'D:/folder' *not* 'd:/folder'. ''' mo...
Finalize options to be used.
def finalize_options(self): '''Finalize options to be used.''' self.resource_source_path = os.path.join(RESOURCE_PATH, 'resource.qrc') self.resource_target_path = RESOURCE_TARGET_PATH
Run build.
def run(self): '''Run build.''' if ON_READ_THE_DOCS: # PySide not available. return try: pyside_rcc_command = 'pyside-rcc' # On Windows, pyside-rcc is not automatically available on the # PATH so try to find it manually. i...
Run clean.
def run(self): '''Run clean.''' relative_resource_path = os.path.relpath( RESOURCE_TARGET_PATH, ROOT_PATH ) if os.path.exists(relative_resource_path): os.remove(relative_resource_path) else: distutils.log.warn( '\'{0}\' does not...
Return appropriate: py: class: Item instance for * path *.
def ItemFactory(path): '''Return appropriate :py:class:`Item` instance for *path*. If *path* is null then return Computer root. ''' if not path: return Computer() elif os.path.isfile(path): return File(path) elif os.path.ismount(path): return Mount(path) elif os....
Add * item * as child of this item.
def addChild(self, item): '''Add *item* as child of this item.''' if item.parent and item.parent != self: item.parent.removeChild(item) self.children.append(item) item.parent = self
Fetch and return new children.
def fetchChildren(self): '''Fetch and return new children. Will only fetch children whilst canFetchMore is True. .. note:: It is the caller's responsibility to add each fetched child to this parent if desired using :py:meth:`Item.addChild`. ''' if not ...
Reload children.
def refetch(self): '''Reload children.''' # Reset children for child in self.children[:]: self.removeChild(child) # Enable children fetching self._fetched = False
Fetch and return new child items.
def _fetchChildren(self): '''Fetch and return new child items.''' children = [] for entry in QDir.drives(): path = os.path.normpath(entry.canonicalFilePath()) children.append(Mount(path)) return children
Fetch and return new child items.
def _fetchChildren(self): '''Fetch and return new child items.''' children = [] # List paths under this directory. paths = [] for name in os.listdir(self.path): paths.append(os.path.normpath(os.path.join(self.path, name))) # Handle collections. colle...
Fetch and return new child items.
def _fetchChildren(self): '''Fetch and return new child items.''' children = [] for path in self._collection: try: child = ItemFactory(path) except ValueError: pass else: children.append(child) return ch...
Return number of children * parent * index has.
def rowCount(self, parent): '''Return number of children *parent* index has.''' if parent.column() > 0: return 0 if parent.isValid(): item = parent.internalPointer() else: item = self.root return len(item.children)
Return index for * row * and * column * under * parent *.
def index(self, row, column, parent): '''Return index for *row* and *column* under *parent*.''' if not self.hasIndex(row, column, parent): return QModelIndex() if not parent.isValid(): item = self.root else: item = parent.internalPointer() tr...
Return index of item with * path *.
def pathIndex(self, path): '''Return index of item with *path*.''' if path == self.root.path: return QModelIndex() if not path.startswith(self.root.path): return QModelIndex() parts = [] while True: if path == self.root.path: ...