_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q241700
DuplicateSet.delete_bigger
train
def delete_bigger(self): """ Delete all bigger duplicates. Only keeps the subset sharing the smallest size. """ logger.info( "Deleting all mails strictly bigger than {} bytes...".format( self.smallest_size)) # Select candidates for deletion. c...
python
{ "resource": "" }
q241701
DuplicateSet.delete_biggest
train
def delete_biggest(self): """ Delete all the biggest duplicates. Keeps all mail of the duplicate set but those sharing the biggest size. """ logger.info( "Deleting all mails sharing the biggest size of {} bytes..." "".format(self.biggest_size)) # ...
python
{ "resource": "" }
q241702
DuplicateSet.delete_matching_path
train
def delete_matching_path(self): """ Delete all duplicates whose file path match the regexp. """ logger.info( "Deleting all mails with file path matching the {} regexp..." "".format(self.conf.regexp.pattern)) # Select candidates for deletion. candidates = [ ...
python
{ "resource": "" }
q241703
Deduplicate.canonical_path
train
def canonical_path(path): """ Return a normalized, canonical path to a file or folder. Removes all symbolic links encountered in the path to detect natural mail and maildir duplicates on the fly. """ return os.path.normcase(os.path.realpath(os.path.abspath( os.path.e...
python
{ "resource": "" }
q241704
Deduplicate.add_maildir
train
def add_maildir(self, maildir_path): """ Load up a maildir and compute hash for each mail found. """ maildir_path = self.canonical_path(maildir_path) logger.info("Opening maildir at {} ...".format(maildir_path)) # Maildir parser requires a string, not a unicode, as path. maildir ...
python
{ "resource": "" }
q241705
Deduplicate.run
train
def run(self): """ Run the deduplication process. We apply the removal strategy one duplicate set at a time to keep memory footprint low and make the log of actions easier to read. """ logger.info( "The {} strategy will be applied on each duplicate set.".format( ...
python
{ "resource": "" }
q241706
Deduplicate.report
train
def report(self): """ Print user-friendly statistics and metrics. """ table = [["Mails", "Metric"]] table.append(["Found", self.stats['mail_found']]) table.append(["Skipped", self.stats['mail_skipped']]) table.append(["Rejected", self.stats['mail_rejected']]) table.append...
python
{ "resource": "" }
q241707
cli
train
def cli(ctx): """ CLI for maildirs content analysis and deletion. """ level = logger.level try: level_to_name = logging._levelToName # Fallback to pre-Python 3.4 internals. except AttributeError: level_to_name = logging._levelNames level_name = level_to_name.get(level, level) ...
python
{ "resource": "" }
q241708
validate_regexp
train
def validate_regexp(ctx, param, value): """ Validate and compile regular expression. """ if value: try: value = re.compile(value) except ValueError: raise click.BadParameter('invalid regular expression.') return value
python
{ "resource": "" }
q241709
validate_maildirs
train
def validate_maildirs(ctx, param, value): """ Check that folders are maildirs. """ for path in value: for subdir in MD_SUBDIRS: if not os.path.isdir(os.path.join(path, subdir)): raise click.BadParameter( '{} is not a maildir (missing {!r} sub-directory).'....
python
{ "resource": "" }
q241710
deduplicate
train
def deduplicate( ctx, strategy, time_source, regexp, dry_run, message_id, size_threshold, content_threshold, show_diff, maildirs): """ Deduplicate mails from a set of maildir folders. Run a first pass computing the canonical hash of each encountered mail from their headers, then a second pa...
python
{ "resource": "" }
q241711
hash
train
def hash(ctx, message_id, message): """ Take a single mail message and show its canonicalised form and hash. Mainly used to debug message hashing. """ conf = Config(message_id=message_id) mail = Mail(message, conf) logger.info(mail.header_text) logger.info('-' * 70) logger.info('Hash:...
python
{ "resource": "" }
q241712
read_file
train
def read_file(*relative_path_elements): """ Return content of a file relative to this ``setup.py``. """ file_path = path.join(path.dirname(__file__), *relative_path_elements) return io.open(file_path, encoding='utf8').read().strip()
python
{ "resource": "" }
q241713
Mail.message
train
def message(self): """ Read mail, parse it and return a Message instance. """ logger.debug("Parsing mail at {} ...".format(self.path)) with open(self.path, 'rb') as mail_file: if PY2: message = email.message_from_file(mail_file) else: messa...
python
{ "resource": "" }
q241714
Mail.timestamp
train
def timestamp(self): """ Compute the normalized canonical timestamp of the mail. """ # XXX ctime does not refer to creation time on POSIX systems, but # rather the last time the inode data changed. Source: # https://userprimary.net/posts/2007/11/18 # /ctime-in-unix-means-last-cha...
python
{ "resource": "" }
q241715
Mail.body_lines
train
def body_lines(self): """ Return a normalized list of lines from message's body. """ if not self.message.is_multipart(): body = self.message.get_payload(None, decode=True) else: _, _, body = self.message.as_string().partition("\n\n") if isinstance(body, bytes): ...
python
{ "resource": "" }
q241716
Mail.subject
train
def subject(self): """ Normalized subject. Only used for debugging and human-friendly logging. """ # Fetch subject from first message. subject = self.message.get('Subject', '') subject, _ = re.subn(r'\s+', ' ', subject) return subject
python
{ "resource": "" }
q241717
Mail.hash_key
train
def hash_key(self): """ Returns the canonical hash of a mail. """ if self.conf.message_id: message_id = self.message.get('Message-Id') if message_id: return message_id.strip() logger.error( "No Message-ID in {}: {}".format(self.path, se...
python
{ "resource": "" }
q241718
Mail.canonical_headers
train
def canonical_headers(self): """ Copy selected headers into a new string. """ canonical_headers = '' for header in HEADERS: if header not in self.message: continue for value in self.message.get_all(header): canonical_value = self.canonica...
python
{ "resource": "" }
q241719
HidTransport.enumerate
train
def enumerate(cls): """ Return a list of available KeepKey devices. """ devices = {} for d in hid.enumerate(0, 0): vendor_id = d['vendor_id'] product_id = d['product_id'] serial_number = d['serial_number'] interface_number = d['inte...
python
{ "resource": "" }
q241720
HidTransport.is_connected
train
def is_connected(self): """ Check if the device is still connected. """ for d in hid.enumerate(0, 0): if d['path'] == self.device: return True return False
python
{ "resource": "" }
q241721
Transport.session_end
train
def session_end(self): """ End a session. Se session_begin for an in depth description of TREZOR sessions. """ self.session_depth -= 1 self.session_depth = max(0, self.session_depth) if self.session_depth == 0: self._session_end()
python
{ "resource": "" }
q241722
Transport.read
train
def read(self): """ If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. Otherwise, returns None. """ if not self.ready_to_read(): return None ...
python
{ "resource": "" }
q241723
Transport.read_blocking
train
def read_blocking(self): """ Same as read, except blocks untill data is available to be read. """ while True: data = self._read() if data != None: break return self._parse_message(data)
python
{ "resource": "" }
q241724
_get_cache_name
train
def _get_cache_name(function): """ returns a name for the module's cache db. """ module_name = _inspect.getfile(function) module_name = _os.path.abspath(module_name) cache_name = module_name # fix for '<string>' or '<stdin>' in exec or interpreter usage. cache_name = cache_name.replace(...
python
{ "resource": "" }
q241725
filecache
train
def filecache(seconds_of_validity=None, fail_silently=False): ''' filecache is called and the decorator should be returned. ''' def filecache_decorator(function): @_functools.wraps(function) def function_with_cache(*args, **kwargs): try: key = _args_key(functi...
python
{ "resource": "" }
q241726
ModelState.entity_data
train
def entity_data(self, entity_type, entity_id, history_index): """Return the data dict for an entity at a specific index of its history. """ return self.entity_history(entity_type, entity_id)[history_index]
python
{ "resource": "" }
q241727
ModelState.get_entity
train
def get_entity( self, entity_type, entity_id, history_index=-1, connected=True): """Return an object instance for the given entity_type and id. By default the object state matches the most recent state from Juju. To get an instance of the object in an older state, pass histo...
python
{ "resource": "" }
q241728
ModelEntity.on_change
train
def on_change(self, callable_): """Add a change observer to this entity. """ self.model.add_observer( callable_, self.entity_type, 'change', self.entity_id)
python
{ "resource": "" }
q241729
ModelEntity.on_remove
train
def on_remove(self, callable_): """Add a remove observer to this entity. """ self.model.add_observer( callable_, self.entity_type, 'remove', self.entity_id)
python
{ "resource": "" }
q241730
ModelEntity.dead
train
def dead(self): """Returns True if this entity no longer exists in the underlying model. """ return ( self.data is None or self.model.state.entity_data( self.entity_type, self.entity_id, -1) is None )
python
{ "resource": "" }
q241731
ModelEntity.previous
train
def previous(self): """Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates. """ return self.mod...
python
{ "resource": "" }
q241732
ModelEntity.next
train
def next(self): """Return a copy of this object at its next state in history. Returns None if this object is already the latest. The returned object is "disconnected", i.e. does not receive live updates, unless it is current (latest). """ if self._history_index...
python
{ "resource": "" }
q241733
Model.connect
train
async def connect(self, *args, **kwargs): """Connect to a juju model. This supports two calling conventions: The model and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``model_name`` is spec...
python
{ "resource": "" }
q241734
Model.add_local_charm_dir
train
async def add_local_charm_dir(self, charm_dir, series): """Upload a local charm to the model. This will automatically generate an archive from the charm dir. :param charm_dir: Path to the charm directory :param series: Charm series """ fh = tempfile.NamedTempor...
python
{ "resource": "" }
q241735
Model.add_local_charm
train
def add_local_charm(self, charm_file, series, size=None): """Upload a local charm archive to the model. Returns the 'local:...' url that should be used to deploy the charm. :param charm_file: Path to charm zip archive :param series: Charm series :param size: Size of the archive...
python
{ "resource": "" }
q241736
Model.all_units_idle
train
def all_units_idle(self): """Return True if all units are idle. """ for unit in self.units.values(): unit_status = unit.data['agent-status']['current'] if unit_status != 'idle': return False return True
python
{ "resource": "" }
q241737
Model.reset
train
async def reset(self, force=False): """Reset the model to a clean state. :param bool force: Force-terminate machines. This returns only after the model has reached a clean state. "Clean" means no applications or machines exist in the model. """ log.debug('Resetting mod...
python
{ "resource": "" }
q241738
Model.get_info
train
async def get_info(self): """Return a client.ModelInfo object for this Model. Retrieves latest info for this Model from the api server. The return value is cached on the Model.info attribute so that the valued may be accessed again without another api call, if desired. ...
python
{ "resource": "" }
q241739
Model.add_observer
train
def add_observer( self, callable_, entity_type=None, action=None, entity_id=None, predicate=None): """Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable a...
python
{ "resource": "" }
q241740
Model._watch
train
def _watch(self): """Start an asynchronous watch against this model. See :meth:`add_observer` to register an onchange callback. """ async def _all_watcher(): try: allwatcher = client.AllWatcherFacade.from_connection( self.connection()) ...
python
{ "resource": "" }
q241741
Model._notify_observers
train
async def _notify_observers(self, delta, old_obj, new_obj): """Call observing callbacks, notifying them of a change in model state :param delta: The raw change from the watcher (:class:`juju.client.overrides.Delta`) :param old_obj: The object in the model that this delta updates. ...
python
{ "resource": "" }
q241742
Model._wait
train
async def _wait(self, entity_type, entity_id, action, predicate=None): """ Block the calling routine until a given action has happened to the given entity :param entity_type: The entity's type. :param entity_id: The entity's id. :param action: the type of action (e.g., '...
python
{ "resource": "" }
q241743
Model._wait_for_new
train
async def _wait_for_new(self, entity_type, entity_id): """Wait for a new object to appear in the Model and return it. Waits for an object of type ``entity_type`` with id ``entity_id`` to appear in the model. This is similar to watching for the object using ``block_until``, but uses the...
python
{ "resource": "" }
q241744
Model.wait_for_action
train
async def wait_for_action(self, action_id): """Given an action, wait for it to complete.""" if action_id.startswith("action-"): # if we've been passed action.tag, transform it into the # id that the api deltas will use. action_id = action_id[7:] def predicat...
python
{ "resource": "" }
q241745
Model.add_machine
train
async def add_machine( self, spec=None, constraints=None, disks=None, series=None): """Start a new, empty machine and optionally a container, or add a container to a machine. :param str spec: Machine specification Examples:: (None) - starts a new machine...
python
{ "resource": "" }
q241746
Model.add_relation
train
async def add_relation(self, relation1, relation2): """Add a relation between two applications. :param str relation1: '<application>[:<relation_name>]' :param str relation2: '<application>[:<relation_name>]' """ connection = self.connection() app_facade = client.Applica...
python
{ "resource": "" }
q241747
Model.add_ssh_key
train
async def add_ssh_key(self, user, key): """Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key """ key_facade = client.KeyManagerFacade.from_connection(self.connection()) return await key_facade.AddKeys([key],...
python
{ "resource": "" }
q241748
Model.debug_log
train
def debug_log( self, no_tail=False, exclude_module=None, include_module=None, include=None, level=None, limit=0, lines=10, replay=False, exclude=None): """Get log messages for this model. :param bool no_tail: Stop after returning existing log messages :param ...
python
{ "resource": "" }
q241749
Model._deploy
train
async def _deploy(self, charm_url, application, series, config, constraints, endpoint_bindings, resources, storage, channel=None, num_units=None, placement=None, devices=None): """Logic shared between `Model.deploy` and `BundleHandler.deploy`. ...
python
{ "resource": "" }
q241750
Model.destroy_unit
train
async def destroy_unit(self, *unit_names): """Destroy units by name. """ connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Destroying unit%s %s', 's' if len(unit_names) == 1 else '', ...
python
{ "resource": "" }
q241751
Model.get_config
train
async def get_config(self): """Return the configuration settings for this model. :returns: A ``dict`` mapping keys to `ConfigValue` instances, which have `source` and `value` attributes. """ config_facade = client.ModelConfigFacade.from_connection( self.connectio...
python
{ "resource": "" }
q241752
Model.get_constraints
train
async def get_constraints(self): """Return the machine constraints for this model. :returns: A ``dict`` of constraints. """ constraints = {} client_facade = client.ClientFacade.from_connection(self.connection()) result = await client_facade.GetModelConstraints() ...
python
{ "resource": "" }
q241753
Model.restore_backup
train
def restore_backup( self, bootstrap=False, constraints=None, archive=None, backup_id=None, upload_tools=False): """Restore a backup archive to a new controller. :param bool bootstrap: Bootstrap a new state machine :param constraints: Model constraints :type const...
python
{ "resource": "" }
q241754
Model.set_config
train
async def set_config(self, config): """Set configuration keys on this model. :param dict config: Mapping of config keys to either string values or `ConfigValue` instances, as returned by `get_config`. """ config_facade = client.ModelConfigFacade.from_connection( ...
python
{ "resource": "" }
q241755
Model.set_constraints
train
async def set_constraints(self, constraints): """Set machine constraints on this model. :param dict config: Mapping of model constraints """ client_facade = client.ClientFacade.from_connection(self.connection()) await client_facade.SetModelConstraints( application=''...
python
{ "resource": "" }
q241756
Model.get_action_output
train
async def get_action_output(self, action_uuid, wait=None): """Get the results of an action by ID. :param str action_uuid: Id of the action :param int wait: Time in seconds to wait for action to complete. :return dict: Output from action :raises: :class:`JujuError` if invalid act...
python
{ "resource": "" }
q241757
Model.get_action_status
train
async def get_action_status(self, uuid_or_prefix=None, name=None): """Get the status of all actions, filtered by ID, ID prefix, or name. :param str uuid_or_prefix: Filter by action uuid or prefix :param str name: Filter by action name """ results = {} action_results = [...
python
{ "resource": "" }
q241758
Model.get_status
train
async def get_status(self, filters=None, utc=False): """Return the status of the model. :param str filters: Optional list of applications, units, or machines to include, which can use wildcards ('*'). :param bool utc: Display time as UTC in RFC3339 format """ client...
python
{ "resource": "" }
q241759
Model.sync_tools
train
def sync_tools( self, all_=False, destination=None, dry_run=False, public=False, source=None, stream=None, version=None): """Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination direct...
python
{ "resource": "" }
q241760
Model.upgrade_juju
train
def upgrade_juju( self, dry_run=False, reset_previous_upgrade=False, upload_tools=False, version=None): """Upgrade Juju on all machines in a model. :param bool dry_run: Don't do the actual upgrade :param bool reset_previous_upgrade: Clear the previous (incomplete) ...
python
{ "resource": "" }
q241761
Model.get_metrics
train
async def get_metrics(self, *tags): """Retrieve metrics. :param str *tags: Tags of entities from which to retrieve metrics. No tags retrieves the metrics of all units in the model. :return: Dictionary of unit_name:metrics """ log.debug("Retrieving metrics for %s", ...
python
{ "resource": "" }
q241762
BundleHandler.scale
train
async def scale(self, application, scale): """ Handle a change of scale to a k8s application. :param string application: Application holds the application placeholder name for which a unit is added. :param int scale: New scale value to use. "...
python
{ "resource": "" }
q241763
CharmArchiveGenerator.make_archive
train
def make_archive(self, path): """Create archive of directory and write to ``path``. :param path: Path to archive Ignored:: * build/* - This is used for packing the charm itself and any similar tasks. * */.* - Hidden files are all ignored fo...
python
{ "resource": "" }
q241764
CharmArchiveGenerator._check_type
train
def _check_type(self, path): """Check the path """ s = os.stat(path) if stat.S_ISDIR(s.st_mode) or stat.S_ISREG(s.st_mode): return path raise ValueError("Invalid Charm at % %s" % ( path, "Invalid file type for a charm"))
python
{ "resource": "" }
q241765
CharmArchiveGenerator._write_symlink
train
def _write_symlink(self, zf, link_target, link_path): """Package symlinks with appropriate zipfile metadata.""" info = zipfile.ZipInfo() info.filename = link_path info.create_system = 3 # Magic code for symlinks / py2/3 compat # 27166663808 = (stat.S_IFLNK | 0755) << 16 ...
python
{ "resource": "" }
q241766
User.set_password
train
async def set_password(self, password): """Update this user's password. """ await self.controller.change_user_password(self.username, password) self._user_info.password = password
python
{ "resource": "" }
q241767
User.grant
train
async def grant(self, acl='login'): """Set access level of this user on the controller. :param str acl: Access control ('login', 'add-model', or 'superuser') """ if await self.controller.grant(self.username, acl): self._user_info.access = acl
python
{ "resource": "" }
q241768
User.revoke
train
async def revoke(self): """Removes all access rights for this user from the controller. """ await self.controller.revoke(self.username) self._user_info.access = ''
python
{ "resource": "" }
q241769
User.disable
train
async def disable(self): """Disable this user. """ await self.controller.disable_user(self.username) self._user_info.disabled = True
python
{ "resource": "" }
q241770
User.enable
train
async def enable(self): """Re-enable this user. """ await self.controller.enable_user(self.username) self._user_info.disabled = False
python
{ "resource": "" }
q241771
Machine.destroy
train
async def destroy(self, force=False): """Remove this machine from the model. Blocks until the machine is actually removed. """ facade = client.ClientFacade.from_connection(self.connection) log.debug( 'Destroying machine %s', self.id) await facade.DestroyMa...
python
{ "resource": "" }
q241772
Machine.scp_to
train
async def scp_to(self, source, destination, user='ubuntu', proxy=False, scp_opts=''): """Transfer files to this machine. :param str source: Local path of file(s) to transfer :param str destination: Remote destination of transferred files :param str user: Remote user...
python
{ "resource": "" }
q241773
Machine._scp
train
async def _scp(self, source, destination, scp_opts): """ Execute an scp command. Requires a fully qualified source and destination. """ cmd = [ 'scp', '-i', os.path.expanduser('~/.local/share/juju/ssh/juju_id_rsa'), '-o', 'StrictHostKeyChecking=no', ...
python
{ "resource": "" }
q241774
Machine.agent_version
train
def agent_version(self): """Get the version of the Juju machine agent. May return None if the agent is not yet available. """ version = self.safe_data['agent-status']['version'] if version: return client.Number.from_json(version) else: return None
python
{ "resource": "" }
q241775
Machine.dns_name
train
def dns_name(self): """Get the DNS name for this machine. This is a best guess based on the addresses available in current data. May return None if no suitable address is found. """ for scope in ['public', 'local-cloud']: addresses = self.safe_data['addresses'] or []...
python
{ "resource": "" }
q241776
TypeFactory.from_connection
train
def from_connection(cls, connection): """ Given a connected Connection object, return an initialized and connected instance of an API Interface matching the name of this class. @param connection: initialized Connection object. """ facade_name = cls.__name__ ...
python
{ "resource": "" }
q241777
execute_process
train
async def execute_process(*cmd, log=None, loop=None): ''' Wrapper around asyncio.create_subprocess_exec. ''' p = await asyncio.create_subprocess_exec( *cmd, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, loop=loop) ...
python
{ "resource": "" }
q241778
_read_ssh_key
train
def _read_ssh_key(): ''' Inner function for read_ssh_key, suitable for passing to our Executor. ''' default_data_dir = Path(Path.home(), ".local", "share", "juju") juju_data = os.environ.get("JUJU_DATA", default_data_dir) ssh_key_path = Path(juju_data, 'ssh', 'juju_id_rsa.pub') with ssh...
python
{ "resource": "" }
q241779
run_with_interrupt
train
async def run_with_interrupt(task, *events, loop=None): """ Awaits a task while allowing it to be interrupted by one or more `asyncio.Event`s. If the task finishes without the events becoming set, the results of the task will be returned. If the event become set, the task will be cancelled ``N...
python
{ "resource": "" }
q241780
go_to_py_cookie
train
def go_to_py_cookie(go_cookie): '''Convert a Go-style JSON-unmarshaled cookie into a Python cookie''' expires = None if go_cookie.get('Expires') is not None: t = pyrfc3339.parse(go_cookie['Expires']) expires = t.timestamp() return cookiejar.Cookie( version=0, name=go_cook...
python
{ "resource": "" }
q241781
py_to_go_cookie
train
def py_to_go_cookie(py_cookie): '''Convert a python cookie to the JSON-marshalable Go-style cookie form.''' # TODO (perhaps): # HttpOnly # Creation # LastAccess # Updated # not done properly: CanonicalHost. go_cookie = { 'Name': py_cookie.name, 'Value': py_cookie....
python
{ "resource": "" }
q241782
GoCookieJar._really_load
train
def _really_load(self, f, filename, ignore_discard, ignore_expires): '''Implement the _really_load method called by FileCookieJar to implement the actual cookie loading''' data = json.load(f) or [] now = time.time() for cookie in map(go_to_py_cookie, data): if not ign...
python
{ "resource": "" }
q241783
GoCookieJar.save
train
def save(self, filename=None, ignore_discard=False, ignore_expires=False): '''Implement the FileCookieJar abstract method.''' if filename is None: if self.filename is not None: filename = self.filename else: raise ValueError(cookiejar.MISSING_FILEN...
python
{ "resource": "" }
q241784
Controller.connect
train
async def connect(self, *args, **kwargs): """Connect to a Juju controller. This supports two calling conventions: The controller and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``controller...
python
{ "resource": "" }
q241785
Controller.add_credential
train
async def add_credential(self, name=None, credential=None, cloud=None, owner=None, force=False): """Add or update a credential to the controller. :param str name: Name of new credential. If None, the default local credential is used. Name must be provided if a ...
python
{ "resource": "" }
q241786
Controller.add_model
train
async def add_model( self, model_name, cloud_name=None, credential_name=None, owner=None, config=None, region=None): """Add a model to this controller. :param str model_name: Name to give the new model. :param str cloud_name: Name of the cloud in which to create the ...
python
{ "resource": "" }
q241787
Controller.destroy_models
train
async def destroy_models(self, *models, destroy_storage=False): """Destroy one or more models. :param str *models: Names or UUIDs of models to destroy :param bool destroy_storage: Whether or not to destroy storage when destroying the models. Defaults to false. """ u...
python
{ "resource": "" }
q241788
Controller.add_user
train
async def add_user(self, username, password=None, display_name=None): """Add a user to this controller. :param str username: Username :param str password: Password :param str display_name: Display name :returns: A :class:`~juju.user.User` instance """ if not disp...
python
{ "resource": "" }
q241789
Controller.remove_user
train
async def remove_user(self, username): """Remove a user from this controller. """ client_facade = client.UserManagerFacade.from_connection( self.connection()) user = tag.user(username) await client_facade.RemoveUser([client.Entity(user)])
python
{ "resource": "" }
q241790
Controller.change_user_password
train
async def change_user_password(self, username, password): """Change the password for a user in this controller. :param str username: Username :param str password: New password """ user_facade = client.UserManagerFacade.from_connection( self.connection()) ent...
python
{ "resource": "" }
q241791
Controller.reset_user_password
train
async def reset_user_password(self, username): """Reset user password. :param str username: Username :returns: A :class:`~juju.user.User` instance """ user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(u...
python
{ "resource": "" }
q241792
Controller.destroy
train
async def destroy(self, destroy_all_models=False): """Destroy this controller. :param bool destroy_all_models: Destroy all hosted models in the controller. """ controller_facade = client.ControllerFacade.from_connection( self.connection()) return await c...
python
{ "resource": "" }
q241793
Controller.disable_user
train
async def disable_user(self, username): """Disable a user. :param str username: Username """ user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) return await user_facade.DisableUser([entity])
python
{ "resource": "" }
q241794
Controller.enable_user
train
async def enable_user(self, username): """Re-enable a previously disabled user. """ user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) return await user_facade.EnableUser([entity])
python
{ "resource": "" }
q241795
Controller.get_cloud
train
async def get_cloud(self): """ Get the name of the cloud that this controller lives on. """ cloud_facade = client.CloudFacade.from_connection(self.connection()) result = await cloud_facade.Clouds() cloud = list(result.clouds.keys())[0] # only lives on one cloud ...
python
{ "resource": "" }
q241796
Controller.model_uuids
train
async def model_uuids(self): """Return a mapping of model names to UUIDs. """ controller_facade = client.ControllerFacade.from_connection( self.connection()) for attempt in (1, 2, 3): try: response = await controller_facade.AllModels() ...
python
{ "resource": "" }
q241797
Controller.get_model
train
async def get_model(self, model): """Get a model by name or UUID. :param str model: Model name or UUID :returns Model: Connected Model instance. """ uuids = await self.model_uuids() if model in uuids: uuid = uuids[model] else: uuid = model...
python
{ "resource": "" }
q241798
Controller.get_user
train
async def get_user(self, username, secret_key=None): """Get a user by name. :param str username: Username :param str secret_key: Issued by juju when add or reset user password :returns: A :class:`~juju.user.User` instance """ client_facade = client.UserManage...
python
{ "resource": "" }
q241799
Controller.get_users
train
async def get_users(self, include_disabled=False): """Return list of users that can connect to this controller. :param bool include_disabled: Include disabled users :returns: A list of :class:`~juju.user.User` instances """ client_facade = client.UserManagerFacade.from_connectio...
python
{ "resource": "" }