Search is not available for this dataset
text
stringlengths
75
104k
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 \ ...
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...
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...
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
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
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
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)) ...
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: ...
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: ...
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 = ...
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...
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()
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 ...
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 ...
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' )
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...
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: ...
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...
def stop(self): """Stop this client. """ self.t.stop() self.factory.stopTrying() self.connector.disconnect()
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...
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] ...
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...
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)...
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) ...
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...
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, ...
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()
def decodeMessage(self, data): """Decode a protobuf message into a list of Tensor events""" message = proto_pb2.Msg() message.ParseFromString(data) return message
def sendEvents(self, events): """Send a Tensor Event to Riemann""" self.pressure += 1 self.sendString(self.encodeMessage(events))
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...
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)
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...
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) ...
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...
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...
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
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_...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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))
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...
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...
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...
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 ...
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...
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]])
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)
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...
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() ...
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...
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...
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)
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)
def _onNavigate(self, index): '''Handle selection of path segment.''' if index > 0: self.setLocation( self._locationWidget.itemData(index), interactive=True )
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 ...
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'. ...
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...
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
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...
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...
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....
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
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 ...
def refetch(self): '''Reload children.''' # Reset children for child in self.children[:]: self.removeChild(child) # Enable children fetching self._fetched = False
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
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...
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...
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)
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...
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: ...
def parent(self, index): '''Return parent of *index*.''' if not index.isValid(): return QModelIndex() item = index.internalPointer() if not item: return QModelIndex() parent = item.parent if not parent or parent == self.root: return Q...
def data(self, index, role): '''Return data for *index* according to *role*.''' if not index.isValid(): return None column = index.column() item = index.internalPointer() if role == self.ITEM_ROLE: return item elif role == Qt.DisplayRole: ...
def headerData(self, section, orientation, role): '''Return label for *section* according to *orientation* and *role*.''' if orientation == Qt.Horizontal: if section < len(self.columns): column = self.columns[section] if role == Qt.DisplayRole: ...
def hasChildren(self, index): '''Return if *index* has children. Optimised to avoid loading children at this stage. ''' if not index.isValid(): item = self.root else: item = index.internalPointer() if not item: return False ...
def canFetchMore(self, index): '''Return if more data available for *index*.''' if not index.isValid(): item = self.root else: item = index.internalPointer() return item.canFetchMore()
def fetchMore(self, index): '''Fetch additional data under *index*.''' if not index.isValid(): item = self.root else: item = index.internalPointer() if item.canFetchMore(): startIndex = len(item.children) additionalChildren = item.fetchChi...
def lessThan(self, left, right): '''Return ordering of *left* vs *right*.''' sourceModel = self.sourceModel() if sourceModel: leftItem = sourceModel.item(left) rightItem = sourceModel.item(right) if (isinstance(leftItem, Directory) and not isi...
def pathIndex(self, path): '''Return index of item with *path*.''' sourceModel = self.sourceModel() if not sourceModel: return QModelIndex() return self.mapFromSource(sourceModel.pathIndex(path))
def item(self, index): '''Return item at *index*.''' sourceModel = self.sourceModel() if not sourceModel: return None return sourceModel.item(self.mapToSource(index))
def icon(self, index): '''Return icon for index.''' sourceModel = self.sourceModel() if not sourceModel: return None return sourceModel.icon(self.mapToSource(index))
def hasChildren(self, index): '''Return if *index* has children.''' sourceModel = self.sourceModel() if not sourceModel: return False return sourceModel.hasChildren(self.mapToSource(index))
def canFetchMore(self, index): '''Return if more data available for *index*.''' sourceModel = self.sourceModel() if not sourceModel: return False return sourceModel.canFetchMore(self.mapToSource(index))
def fetchMore(self, index): '''Fetch additional data under *index*.''' sourceModel = self.sourceModel() if not sourceModel: return False return sourceModel.fetchMore(self.mapToSource(index))
def icon(self, specification): '''Return appropriate icon for *specification*. *specification* should be either: * An instance of :py:class:`riffle.model.Item` * One of the defined icon types (:py:class:`IconType`) ''' if isinstance(specification, riffle.model....
def type(self, item): '''Return appropriate icon type for *item*.''' iconType = IconType.Unknown if isinstance(item, riffle.model.Computer): iconType = IconType.Computer elif isinstance(item, riffle.model.Mount): iconType = IconType.Mount elif isinstanc...
def call(args, stdout=None, stderr=None, stdin=None, daemonize=False, preexec_fn=None, shell=False, cwd=None, env=None): """ Run an external command in a separate process and detach it from the current process. Excepting `stdout`, `stderr`, and `stdin` all file descriptors are closed after forking....
def _get_max_fd(self): """Return the maximum file descriptor value.""" limits = resource.getrlimit(resource.RLIMIT_NOFILE) result = limits[1] if result == resource.RLIM_INFINITY: result = maxfd return result
def _close_fd(self, fd): """Close a file descriptor if it is open.""" try: os.close(fd) except OSError, exc: if exc.errno != errno.EBADF: msg = "Failed to close file descriptor {}: {}".format(fd, exc) raise Error(msg)
def _close_open_fds(self): """Close open file descriptors.""" maxfd = self._get_max_fd() for fd in reversed(range(maxfd)): if fd not in self.exclude_fds: self._close_fd(fd)
def _redirect(self, stream, target): """Redirect a system stream to the provided target.""" if target is None: target_fd = os.open(os.devnull, os.O_RDWR) else: target_fd = target.fileno() os.dup2(target_fd, stream.fileno())
def set_form_widgets_attrs(form, attrs): """Applies a given HTML attributes to each field widget of a given form. Example: set_form_widgets_attrs(my_form, {'class': 'clickable'}) """ for _, field in form.fields.items(): attrs_ = dict(attrs) for name, val in attrs.items(): ...
def get_model_class_from_string(model_path): """Returns a certain model as defined in a string formatted `<app_name>.<model_name>`. Example: model = get_model_class_from_string('myapp.MyModel') """ try: app_name, model_name = model_path.split('.') except ValueError: raise ...