Search is not available for this dataset
text
stringlengths
75
104k
def _distribute_jobs(self): """ Distributes jobs from the active job set to any waiting get_job callbacks. """ while (self._active_js.job_available() and len(self._ready_callbacks) > 0): job = self._active_js.get_job() self._job_sources[jo...
def add_job_set(self, job_list): """ Adds a job set to the manager's queue. If there is no job set running, it is activated immediately. A new job set handle is returned. """ assert not self._closed results = Results(loop=self._loop) js = JobSet(job_list, result...
def get_job(self, callback): """ Calls the given callback function when a job becomes available. """ assert not self._closed if self._active_js is None or not self._active_js.job_available(): self._ready_callbacks.append(callback) else: job = sel...
def return_job(self, job): """ Returns a job to its source job set to be run again later. """ if self._closed: return js = self._job_sources[job] if len(self._ready_callbacks) > 0: callback = self._ready_callbacks.popleft() callback(j...
def add_result(self, job, result): """ Adds the result of a job to the results list of the job's source job set. """ if self._closed: return js = self._job_sources[job] del self._job_sources[job] js.add_result(result)
def job_set_done(self, js): """ Called when a job set has been completed or cancelled. If the job set was active, the next incomplete job set is loaded from the job set queue and is activated. """ if self._closed: return if self._active_js != js: ...
def close(self): """ Closes the job manager. No more jobs will be assigned, no more job sets will be added, and any queued or active job sets will be cancelled. """ if self._closed: return self._closed = True if self._active_js is not None: ...
def entry_point(items=tuple()): """ External entry point which calls main() and if Stop is raised, calls sys.exit() """ try: if not items: from .example import ExampleCommand from .version import Version items = [(ExampleCommand.NAME, ExampleCommand), ...
def _uniquify(_list): """Remove duplicates in a list.""" seen = set() result = [] for x in _list: if x not in seen: result.append(x) seen.add(x) return result
def _match_regex(regex, obj): """ Returns true if the regex matches the object, or a string in the object if it is some sort of container. :param regex: A regex. :type regex: ``regex`` :param obj: An arbitrary object. :type object: ``object`` :rtype: ``bool`` """ if isinstance(...
def get_entries(latest, filters, exclude, limit=None): """ Lists all available instances. :param latest: If true, ignores the cache and grabs the latest list. :type latest: ``bool`` :param filters: Filters to apply to results. A result will only be shown if it includes all text ...
def get_region(): """Use the environment to get the current region""" global _REGION if _REGION is None: region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1" region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")} if region_name not in region_dict: r...
def _is_valid_cache(): """ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` """ if not os.path.exists(get_cache_location()): return False modified = os.path.getmtime(get_cache_location()) modified = tim...
def _list_all_cached(): """ Reads the description cache, returning each instance's information. :return: A list of host entries. :rtype: [:py:class:`HostEntry`] """ with open(get_cache_location()) as f: contents = f.read() objects = json.loads(contents) return [HostEntry....
def filter_entries(entries, filters, exclude): """ Filters a list of host entries according to the given filters. :param entries: A list of host entries. :type entries: [:py:class:`HostEntry`] :param filters: Regexes that must match a `HostEntry`. :type filters: [``str``] :param exclude: Re...
def get_host(name): """ Prints the public dns name of `name`, if it exists. :param name: The instance name. :type name: ``str`` """ f = {'instance-state-name': 'running', 'tag:Name': name} ec2 = boto.connect_ec2(region=get_region()) rs = ec2.get_all_instances(filters=f) if len(rs) =...
def from_dict(cls, entry_dict): """Deserialize a HostEntry from a dictionary. This is more or less the same as calling HostEntry(**entry_dict), but is clearer if something is missing. :param entry_dict: A dictionary in the format outputted by to_dict(). :type entry_dict...
def _get_attrib(self, attr, convert_to_str=False): """ Given an attribute name, looks it up on the entry. Names that start with ``tags.`` are looked up in the ``tags`` dictionary. :param attr: Name of attribute to look up. :type attr: ``str`` :param convert_to_str: Conve...
def list_attributes(cls): """ Lists all of the attributes to be found on an instance of this class. It creates a "fake instance" by passing in `None` to all of the ``__init__`` arguments, then returns all of the attributes of that instance. :return: A list of instance at...
def sort_by(cls, entries, attribute): """ Sorts a list of entries by the given attribute. """ def key(entry): return entry._get_attrib(attribute, convert_to_str=True) return sorted(entries, key=key)
def repr_as_line(self, additional_columns=None, only_show=None, sep=','): """ Returns a representation of the host as a single line, with columns joined by ``sep``. :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` ...
def from_boto_instance(cls, instance): """ Loads a ``HostEntry`` from a boto instance. :param instance: A boto instance object. :type instance: :py:class:`boto.ec2.instanceInstance` :rtype: :py:class:`HostEntry` """ return cls( name=instance.tags.get...
def matches(self, _filter): """ Returns whether the instance matches the given filter text. :param _filter: A regex filter. If it starts with `<identifier>:`, then the part before the colon will be used as an attribute and the part after will be a...
def display(self): """ Returns the best name to display for this host. Uses the instance name if available; else just the public IP. :rtype: ``str`` """ if isinstance(self.name, six.string_types) and len(self.name) > 0: return '{0} ({1})'.format(self.name, se...
def prettyname(cls, attrib_name): """ Returns the "pretty name" (capitalized, etc) of an attribute, by looking it up in ``cls.COLUMN_NAMES`` if it exists there. :param attrib_name: An attribute name. :type attrib_name: ``str`` :rtype: ``str`` """ if attr...
def format_string(self, fmat_string): """ Takes a string containing 0 or more {variables} and formats it according to this instance's attributes. :param fmat_string: A string, e.g. '{name}-foo.txt' :type fmat_string: ``str`` :return: The string formatted according to th...
def render_entries(cls, entries, additional_columns=None, only_show=None, numbers=False): """ Pretty-prints a list of entries. If the window is wide enough to support printing as a table, runs the `print_table.render_table` function on the table. Otherwise, constru...
def add_timestamp(logger_class, log_method, event_dict): ''' Attach the event time, as unix epoch ''' event_dict['timestamp'] = calendar.timegm(time.gmtime()) return event_dict
def setup(level='debug', output=None): ''' Hivy formated logger ''' output = output or settings.LOG['file'] level = level.upper() handlers = [ logbook.NullHandler() ] if output == 'stdout': handlers.append( logbook.StreamHandler(sys.stdout, ...
def logger(name=__name__, output=None, uuid=False, timestamp=False): ''' Configure and return a new logger for hivy modules ''' processors = [] if output == 'json': processors.append(structlog.processors.JSONRenderer()) if uuid: processors.append(add_unique_id) if uuid: proc...
def setup(title, output='json', timezone=None): ''' Implement celery workers using json and redis ''' timezone = timezone or dna.time_utils._detect_timezone() broker_url = 'redis://{}:{}/{}'.format( os.environ.get('BROKER_HOST', 'localhost'), os.environ.get('BROKER_PORT', 6379), 0 ...
def get(self, worker_id): ''' Return status report ''' code = 200 if worker_id == 'all': report = {'workers': [{ 'id': job, 'report': self._inspect_worker(job)} for job in self.jobs] } elif worker_id in self.jobs: ...
def delete(self, worker_id): ''' Stop and remove a worker ''' code = 200 if worker_id in self.jobs: # NOTE pop it if done ? self.jobs[worker_id]['worker'].revoke(terminate=True) report = { 'id': worker_id, 'revoked': True ...
def main(fw_name, args=None, items=None): """ Reusable entry point. Arguments are parsed via the argparse-subcommands configured via each Command class found in globals(). Stop exceptions are propagated to callers. The name of the framework will be used in logging and similar. """ ...
def switch_opt(default, shortname, help_msg): """Define a switchable ConfOpt. This creates a boolean option. If you use it in your CLI, it can be switched on and off by prepending + or - to its name: +opt / -opt. Args: default (bool): the default value of the swith option. shortname (s...
def config_conf_section(): """Define a configuration section handling config file. Returns: dict of ConfOpt: it defines the 'create', 'update', 'edit' and 'editor' configuration options. """ config_dict = OrderedDict(( ('create', ConfOpt(None, True, None, {'action': ...
def set_conf_str(conf, optstrs): """Set options from a list of section.option=value string. Args: conf (:class:`~loam.manager.ConfigurationManager`): the conf to update. optstrs (list of str): the list of 'section.option=value' formatted string. """ falsy = ['0', 'no', 'n', ...
def config_cmd_handler(conf, config='config'): """Implement the behavior of a subcmd using config_conf_section Args: conf (:class:`~loam.manager.ConfigurationManager`): it should contain a section created with :func:`config_conf_section` function. config (str): name of the configura...
def create_complete_files(climan, path, cmd, *cmds, zsh_sourceable=False): """Create completion files for bash and zsh. Args: climan (:class:`~loam.cli.CLIManager`): CLI manager. path (path-like): directory in which the config files should be created. It is created if it doesn't exi...
def render_columns(columns, write_borders=True, column_colors=None): """ Renders a list of columns. :param columns: A list of columns, where each column is a list of strings. :type columns: [[``str``]] :param write_borders: Whether to write the top and bottom borders. :type write_borders: ``boo...
def render_row(num, columns, widths, column_colors=None): """ Render the `num`th row of each column in `columns`. :param num: Which row to render. :type num: ``int`` :param columns: The list of columns. :type columns: [[``str``]] :param widths: The widths of each column. :type widths: [...
def render_table(table, write_borders=True, column_colors=None): """ Renders a table. A table is a list of rows, each of which is a list of arbitrary objects. The `.str` method will be called on each element of the row. Jagged tables are ok; in this case, each row will be expanded to the maximum row...
def transpose_table(table): """ Transposes a table, turning rows into columns. :param table: A 2D string grid. :type table: [[``str``]] :return: The same table, with rows and columns flipped. :rtype: [[``str``]] """ if len(table) == 0: return table else: num_columns ...
def prepare_rows(table): """ Prepare the rows so they're all strings, and all the same length. :param table: A 2D grid of anything. :type table: [[``object``]] :return: A table of strings, where every row is the same length. :rtype: [[``str``]] """ num_columns = max(len(row) for row in...
def get_table_width(table): """ Gets the width of the table that would be printed. :rtype: ``int`` """ columns = transpose_table(prepare_rows(table)) widths = [max(len(cell) for cell in column) for column in columns] return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')
def color(number): """ Returns a function that colors a string with a number from 0 to 255. """ if supports_256(): template = "\033[38;5;{number}m{text}\033[0m" else: template = "\033[{number}m{text}\033[0m" def _color(text): if not all([sys.stdout.isatty(), sys.stderr.is...
def get_color_hash(string, _min=MIN_COLOR_BRIGHT, _max=MAX_COLOR_BRIGHT): """ Hashes a string and returns a number between ``min`` and ``max``. """ hash_num = int(hashlib.sha1(string.encode('utf-8')).hexdigest()[:6], 16) _range = _max - _min num_in_range = hash_num % _range return color(_min...
def random_color(_min=MIN_COLOR, _max=MAX_COLOR): """Returns a random color between min and max.""" return color(random.randint(_min, _max))
def get_input(prompt, default=None, exit_msg='bye!'): """ Reads stdin, exits with a message if interrupted, EOF, or a quit message. :return: The entered input. Converts to an integer if possible. :rtype: ``str`` or ``int`` """ try: response = six.moves.input(prompt) except (Keyboard...
def check_credentials(username, password): ''' Verify basic http authentification ''' user = models.User.objects( username=username, password=password ).first() return user or None
def check_token(token): ''' Verify http header token authentification ''' user = models.User.objects(api_key=token).first() return user or None
def requires_basic_auth(resource): ''' Flask decorator protecting ressources using username/password scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided username/password ''' auth = flask.request.authorization user = check_credentials(auth...
def requires_token_auth(resource): ''' Flask decorator protecting ressources using token scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided token ''' token = flask.request.headers.get('Authorization') user = check_token(token) if...
def is_running(process): ''' `pgrep` returns an error code if no process was found ''' try: pgrep = sh.Command('/usr/bin/pgrep') pgrep(process) flag = True except sh.ErrorReturnCode_1: flag = False return flag
def dynamic_import(mod_path, obj_name=None): ''' Take a string and return the corresponding module ''' try: module = __import__(mod_path, fromlist=['whatever']) except ImportError, error: raise errors.DynamicImportFailed( module='.'.join([mod_path, obj_name]), reason=error) #...
def self_ip(public=False): ''' Utility for logbook information injection ''' try: if public: data = str(urlopen('http://checkip.dyndns.com/').read()) ip_addr = re.compile( r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) else: sock = soc...
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): """ Makes the HTTP request using RESTClient. """ if method == "GET": return self.rest_client.GET(url, query_params=query_param...
def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files. """ params = {} if post_params: param...
def serve(self, app_docopt=DEFAULT_DOC, description=''): ''' Configure from cli and run the server ''' exit_status = 0 if isinstance(app_docopt, str): args = docopt(app_docopt, version=description) elif isinstance(app_docopt, dict): args = app_docopt else...
def render(self, name, value, attrs=None): """Include a hidden input to stored the serialized upload value.""" context = attrs or {} context.update({'name': name, 'value': value, }) return render_to_string(self.template_name, context)
def stream_command(command, formatter=None, write_stdin=None, ignore_empty=False): """ Starts `command` in a subprocess. Prints every line the command prints, prefaced with `description`. :param command: The bash command to run. Must use fully-qualified paths. :type command: ``str`` :param form...
def stream_command_dicts(commands, parallel=False): """ Takes a list of dictionaries with keys corresponding to ``stream_command`` arguments, and runs all concurrently. :param commands: A list of dictionaries, the keys of which should line up with the arguments to ``stream_command`...
def stream_commands(commands, hash_colors=True, parallel=False): """ Runs multiple commands, optionally in parallel. Each command should be a dictionary with a 'command' key and optionally 'description' and 'write_stdin' keys. """ def _get_color(string): if hash_colors is True: ...
def networkdays(from_date, to_date, locale='en-US'): """ Return the net work days according to RH's calendar. """ holidays = locales[locale] return workdays.networkdays(from_date, to_date, holidays)
def merge(dicto, other): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``other`` is merged into ``dicto``. :param dicto: dict onto which the merge is execute...
def _run_ssh(entries, username, idfile, no_prompt=False, command=None, show=None, only=None, sort_by=None, limit=None, tunnel=None, num=None, random=False): """ Lets the user choose which instance to SSH into. :param entries: The list of host entries. :type entries: [:py:class...
def _get_path(cmd): """Queries bash to find the path to a commmand on the system.""" if cmd in _PATHS: return _PATHS[cmd] out = subprocess.check_output('which {}'.format(cmd), shell=True) _PATHS[cmd] = out.decode("utf-8").strip() return _PATHS[cmd]
def _build_ssh_command(hostname, username, idfile, ssh_command, tunnel): """Uses hostname and other info to construct an SSH command.""" command = [_get_path('ssh'), '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=5'] if idfile is not None: command.extend(['-i',...
def _build_scp_command(hostname, username, idfile, is_get, local_path, remote_path): """ Uses hostname and other info to construct an SCP command. :param hostname: The hostname of the remote machine. :type hostname: ``str`` :param username: The username to use on the remote m...
def _copy_to(entries, remote_path, local_path, profile): """ Performs an SCP command where the remote_path is the target and the local_path is the source. :param entries: A list of entries. :type entries: ``list`` of :py:class:`HostEntry` :param remote_path: The target path on the remote machin...
def _copy_from(entries, remote_path, local_path, profile): """ Performs an SCP command where the remote_path is the source and the local_path is a format string, formatted individually for each host being copied from so as to create one or more distinct paths on the local system. :param entries...
def _run_ssh_command(entries, username, idfile, command, tunnel, parallel=False): """ Runs the given command over SSH in parallel on all hosts in `entries`. :param entries: The host entries the hostnames from. :type entries: ``list`` of :py:class:`HostEntry` :param username: To...
def _connect_ssh(entry, username, idfile, tunnel=None): """ SSH into to a host. :param entry: The host entry to pull the hostname from. :type entry: :py:class:`HostEntry` :param username: To use a specific username. :type username: ``str`` or ``NoneType`` :param idfile: The SSH identity fil...
def _get_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser(description='List EC2 instances') parser.add_argument('-l', '--latest', action='store_true', default=False, help='Query AWS for latest instances') parser.add_argument('--version', action='store_...
def load(cls, profile_name=None): """Loads the user's LSI profile, or provides a default.""" lsi_location = os.path.expanduser('~/.lsi') if not os.path.exists(lsi_location): return LsiProfile() cfg_parser = ConfigParser() cfg_parser.read(lsi_location) if profi...
def from_args(args): """Takes arguments parsed from argparse and returns a profile.""" # If the args specify a username explicitly, don't load from file. if args.username is not None or args.identity_file is not None: profile = LsiProfile() else: profile = LsiProf...
def merge_(self, merge_dct): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``self``. :param self: dict onto ...
def relate(self, part, id=None): """Relate this package component to the supplied part.""" assert part.name.startswith(self.base) name = part.name[len(self.base):].lstrip('/') rel = Relationship(self, name, part.rel_type, id=id) self.relationships.add(rel) return rel
def related(self, reltype): """Return a list of parts related to this one via reltype.""" parts = [] package = getattr(self, 'package', None) or self for rel in self.relationships.types.get(reltype, []): parts.append(package[posixpath.join(self.base, rel.target)]) return parts
def _load_rels(self, source): """Load relationships from source XML.""" # don't get confused here - the original source is string data; # the parameter source below is a Part object self.relationships.load(source=self, data=source)
def add(self, part, override=True): """Add a part to the package. It will also add a content-type - by default an override. If override is False then it will add a content-type for the extension if one isn't already present. """ ct_add_method = [ self.content_types.add_default, self.content_types.ad...
def _load_part(self, rel_type, name, data): """ Load a part into this package based on its relationship type """ if self.content_types.find_for(name) is None: log.warning('no content type found for part %(name)s' % vars()) return cls = Part.classes_by_rel_type[rel_type] part = cls(self, name) part.l...
def get_parts_by_class(self, cls): """ Return all parts of this package that are instances of cls (where cls is passed directly to isinstance, so can be a class or sequence of classes). """ return (part for part in self.parts.values() if isinstance(part, cls))
def find_for(self, name): """ Get the correct content type for a given name """ map = self.items # first search the overrides (by name) # then fall back to the defaults (by extension) # finally, return None if unmatched return map.get(name, None) or map.get(get_ext(name) or None, None)
def from_element(cls, element): "given an element, parse out the proper ContentType" # disambiguate the subclass ns, class_name = parse_tag(element.tag) class_ = getattr(ContentType, class_name) if not class_: msg = 'Invalid Types child element: %(class_name)s' % vars() raise ValueError(msg) # constru...
def parse(input_string, prefix=''): """Parses the given DSL string and returns parsed results. Args: input_string (str): DSL string prefix (str): Optional prefix to add to every element name, useful to namespace things Returns: dict: Parsed content """ tree = parser.parse(input_string) visit...
def build(self, secret_key): """Builds a final copy of the token using the given secret key. :param secret_key(string): The secret key that corresponds to this builder's access key. """ key = jwk.JWK( kty='oct', k=base64url_encode(uuid.UUID(secret_key).bytes), ...
def assign_force_field(ampal_obj, ff): """Assigns force field parameters to Atoms in the AMPAL object. Parameters ---------- ampal_obj : AMPAL Object Any AMPAL object with a `get_atoms` method. ff: BuffForceField The force field to be used for scoring. """ if hasattr(ampal_o...
def find_max_rad_npnp(self): """Finds the maximum radius and npnp in the force field. Returns ------- (max_rad, max_npnp): (float, float) Maximum radius and npnp distance in the loaded force field. """ max_rad = 0 max_npnp = 0 for res, _ in se...
def _make_ff_params_dict(self): """Makes a dictionary containing PyAtomData for the force field. Returns ------- ff_params_struct_dict: dict Dictionary containing PyAtomData structs for the force field parameters for each atom in the force field. """ ...
def save(self, target=None): """ Save this package to target, which should be a filename or open file stream. If target is not supplied, and this package has a filename attribute (such as when this package was created from an existing file), it will be used. """ target = target or getattr(self, 'filename'...
def as_stream(self): """ Return a zipped package as a readable stream """ stream = io.BytesIO() self._store(stream) stream.seek(0) return stream
def _get_matching_segments(self, zf, name): """ Return a generator yielding each of the segments who's names match name. """ for n in zf.namelist(): if n.startswith(name): yield zf.read(n)
def copy_dir(bucket_name, src_path, dest_path, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None, surrogate_key=None, cache_control=None, surrogate_control=None, create_directory_redirect_object=True): """Copy objects from one direc...
def open_bucket(bucket_name, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None): """Open an S3 Bucket resource. Parameters ---------- bucket_name : `str` Name of the S3 bucket. aws_access_key_id : `str`, optional The access key for ...
def upload_dir(bucket_name, path_prefix, source_dir, upload_dir_redirect_objects=True, surrogate_key=None, surrogate_control=None, cache_control=None, acl=None, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None)...
def upload_file(local_path, bucket_path, bucket, metadata=None, acl=None, cache_control=None): """Upload a file to the S3 bucket. This function uses the mimetypes module to guess and then set the Content-Type and Encoding-Type headers. Parameters ---------- local_path : `str` ...
def upload_object(bucket_path, bucket, content='', metadata=None, acl=None, cache_control=None, content_type=None): """Upload an arbitrary object to an S3 bucket. Parameters ---------- bucket_path : `str` Destination path (also known as the key name) of the f...
def create_dir_redirect_object(bucket_dir_path, bucket, metadata=None, acl=None, cache_control=None): """Create an S3 object representing a directory that's designed to redirect a browser (via Fastly) to the ``index.html`` contained inside that directory. Parameters -...
def list_filenames_in_directory(self, dirname): """List all file-type object names that exist at the root of this bucket directory. Parameters ---------- dirname : `str` Directory name in the bucket relative to ``bucket_root/``. Returns ------- ...