text
stringlengths
81
112k
Return the letter set of this node. def letter_set(self): """ Return the letter set of this node. """ end_str = ctypes.create_string_buffer(MAX_CHARS) cgaddag.gdg_letter_set(self.gdg, self.node, end_str) return [char for char in end_str.value.decode("ascii")]
Return `True` if this `char` is part of this node's letter set, `False` otherwise. def is_end(self, char): """ Return `True` if this `char` is part of this node's letter set, `False` otherwise. """ char = char.lower() return bool(cgaddag.gdg_is_end(self.gdg, sel...
Traverse the GADDAG to the node at the end of the given characters. Args: chars: An string of characters to traverse in the GADDAG. Returns: The Node which is found by traversing the tree. def follow(self, chars): """ Traverse the GADDAG to the node at the end ...
Splits a docker link string into a list of 3 items (protocol, host, port). - Assumes IPv4 Docker links ex: _split_docker_link('DB') -> ['tcp', '172.17.0.82', '8080'] def _split_docker_link(alias_name): """ Splits a docker link string into a list of 3 items (protocol, host, port). - Assumes IPv4 Do...
Get the raw docker link value. Get the raw environment variable for the docker link Args: alias_name: The environment variable name default: The default value if the link isn't available allow_none: If the return value can be `None` (i.e. optional) def read(alias_name, allow_none=Fals...
Return a boolean if the docker link is set or not and is a valid looking docker link value. Args: alias_name: The link alias name def isset(alias_name): """Return a boolean if the docker link is set or not and is a valid looking docker link value. Args: alias_name: The link alias name ...
Get the protocol from the docker link alias or return the default. Args: alias_name: The docker link alias default: The default value if the link isn't available allow_none: If the return value can be `None` (i.e. optional) Examples: Assuming a Docker link was created with ``do...
Get the port from the docker link alias or return the default. Args: alias_name: The docker link alias default: The default value if the link isn't available allow_none: If the return value can be `None` (i.e. optional) Examples: Assuming a Docker link was created with ``docker...
Run the necessary methods in the correct order def runner(self): """ Run the necessary methods in the correct order """ printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime) if not self.pipeline: # If the metadata has been passed from t...
Parses the 16S target files to link accession numbers stored in the .fai and metadata files to the genera stored in the target file def attributer(self): """ Parses the 16S target files to link accession numbers stored in the .fai and metadata files to the genera stored in the target fi...
Creates a report of the results def reporter(self): """ Creates a report of the results """ # Create the path in which the reports are stored make_path(self.reportpath) header = 'Strain,Gene,PercentIdentity,Genus,FoldCoverage\n' data = '' with open(os.pat...
Take a a Flask app and a swagger file in YAML format describing a REST API, and populate the app with routes handling all the paths and methods declared in the swagger file. Also handle marshaling and unmarshaling between json and object instances representing the definitions from the swagger file. de...
Take a bravado-core model representing an error, and return a Flask Response with the given error code and error instance as body def _responsify(api_spec, error, status): """Take a bravado-core model representing an error, and return a Flask Response with the given error code and error instance as body"""...
Generate a handler method for the given url method+path and operation def _generate_handler_wrapper(api_name, api_spec, endpoint, handler_func, error_callback, global_decorator): """Generate a handler method for the given url method+path and operation""" # Decorate the handler function, if Swagger spec tells ...
Returns the ANSI escape sequence to set character formatting. foreground Foreground colour to use. Accepted types: None, int (xterm palette ID), tuple (RGB, RGBA), Colour background Background colour to use. Accepted types: None, int (xterm palette ID), tuple (RGB, RGBA), Colou...
Returns a Unicode string formatted with an ANSI escape sequence. string String to format foreground Foreground colour to use. Accepted types: None, int (xterm palette ID), tuple (RGB, RGBA), Colour background Background colour to use. Accepted types: None, int (xterm ...
Return the ANSI escape sequence to render two vertically-stacked pixels as a single monospace character. top Top colour to use. Accepted types: None, int (xterm palette ID), tuple (RGB, RGBA), Colour bottom Bottom colour to use. Accepted types: None, int (xterm palette ID),...
Return the ANSI escape sequence to render a bitmap image. data_fetch Function that takes three arguments (x position, y position, and frame) and returns a Colour corresponding to the pixel stored there, or Transparent if the requested pixel is out of bounds. x_start Offset fro...
Write a Python object into a byte array, using the field definition. value Input Python object to process. buffer Output byte array to encode value into. parent Parent block object where this Field is defined. Used for e.g. evaluating Refs. def...
Return the end offset of the Field's data. Useful for chainloading. value Input Python object to process. parent Parent block object where this Field is defined. Used for e.g. evaluating Refs. index Index of the Python object to measure from. Us...
Split 'string' along any punctuation or whitespace. def nonalpha_split(string): '''Split 'string' along any punctuation or whitespace.''' return re.findall(r'[%s]+|[^%s]+' % (A, A), string, flags=FLAGS)
Split 'string' into (stressed) syllables and punctuation/whitespace. def syllable_split(string): '''Split 'string' into (stressed) syllables and punctuation/whitespace.''' p = r'\'[%s]+|`[%s]+|[%s]+|[^%s\'`\.]+|[^\.]{1}' % (A, A, A, A) return re.findall(p, string, flags=FLAGS)
Extract all alphabetic syllabified forms from 'string'. def extract_words(string): '''Extract all alphabetic syllabified forms from 'string'.''' return re.findall(r'[%s]+[%s\.]*[%s]+' % (A, A, A), string, flags=FLAGS)
Should define dummyThread class and dummySignal class def init_threads(t=None, s=None): """Should define dummyThread class and dummySignal class""" global THREAD, SIGNAL THREAD = t or dummyThread SIGNAL = s or dummySignal
Return a thread emiting `state_changed` between each sub-requests. :param on_error: callback str -> None :param on_done: callback object -> None :param requete_with_callback: Job to execute. monitor_callable -> None :return: Non started thread def thread_with_callback(on_error, on_done, requete_with_c...
Used to crypt/decrypt data before saving locally. Override if securit is needed. bytes -> str when decrypting str -> bytes when crypting :param datas_str: When crypting, str. when decrypting bytes :param sens: True to crypt, False to decrypt def protege_data(datas_str, sens): """ Used to c...
Build a parser for CLI arguments and options. def build_parser(parser: argparse.ArgumentParser) -> None: """Build a parser for CLI arguments and options.""" parser.add_argument( '--delimiter', help='a delimiter for the samples (teeth) in the key', default=' ', ) parser.add_argum...
Create a parser for CLI arguments and options. def default_parser() -> argparse.ArgumentParser: """Create a parser for CLI arguments and options.""" parser = argparse.ArgumentParser( prog=CONSOLE_SCRIPT, formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) build_parser(parser) ...
Concatenate strings generated by the tooth function. def key( seq: Sequence, tooth: Callable[[Sequence], str] = ( lambda seq: str(random.SystemRandom().choice(seq)).strip() ), nteeth: int = 6, delimiter: str = ' ', ) -> str: """Concatenate strings generated by th...
Execute CLI commands. def main(argv: Sequence[str] = SYS_ARGV) -> int: """Execute CLI commands.""" args = default_parser().parse_args(argv) try: seq = POPULATIONS[args.population] # type: Sequence except KeyError: try: with open(args.population, 'r', encoding=args.encoding...
adds a firewall rule def add_firewalld_service(service, permanent=True): """ adds a firewall rule """ yum_install(packages=['firewalld']) with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): p = '' if permanent: p = '--...
adds a firewall rule def add_firewalld_port(port, permanent=True): """ adds a firewall rule """ yum_install(packages=['firewalld']) log_green('adding a new fw rule: %s' % port) with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): p = ...
adds a new repository file for apt def apt_add_repository_from_apt_string(apt_string, apt_file): """ adds a new repository file for apt """ apt_file_path = '/etc/apt/sources.list.d/%s' % apt_file if not file_contains(apt_file_path, apt_string.lower(), use_sudo=True): file_append(apt_file_path, ap...
returns the current cpu archictecture def arch(): """ returns the current cpu archictecture """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): result = sudo('rpm -E %dist').strip() return result
Set 'UseDNS no' in openssh config to disable rDNS lookups On each request for a new channel openssh defaults to an rDNS lookup on the client IP. This can be slow, if it fails for instance, adding 10s of overhead to every request for a new channel (not connection). This can add a lot of time to a pr...
returns a connection object to AWS EC2 def connect_to_ec2(region, access_key_id, secret_access_key): """ returns a connection object to AWS EC2 """ conn = boto.ec2.connect_to_region(region, aws_access_key_id=access_key_id, aws_secret_...
returns a connection object to Rackspace def connect_to_rackspace(region, access_key_id, secret_access_key): """ returns a connection object to Rackspace """ pyrax.set_setting('identity_type', 'rackspace') pyrax.set_default_region(region) pyrax.set_cre...
Shuts down the instance and creates and image from the disk. Assumes that the disk name is the same as the instance_name (this is the default behavior for boot disks on GCE). def create_gce_image(zone, project, instance_name, name, ...
proxy call for ec2, rackspace create ami backend functions def create_image(cloud, **kwargs): """ proxy call for ec2, rackspace create ami backend functions """ if cloud == 'ec2': return create_ami(**kwargs) if cloud == 'rackspace': return create_rackspace_image(**kwargs) if cloud == ...
Create a new instance def create_server(cloud, **kwargs): """ Create a new instance """ if cloud == 'ec2': _create_server_ec2(**kwargs) elif cloud == 'rackspace': _create_server_rackspace(**kwargs) elif cloud == 'gce': _create_server_gce(**kwargs) else: r...
Perform a GCE operation, blocking until the operation completes. This function will then poll the operation until it reaches state 'DONE' or times out, and then returns the final operation resource dict. :param operation: A dict representing a pending GCE operation resource. :returns dict: A dict...
For now, jclouds is broken for GCE and we will have static slaves in Jenkins. Use this to boot them. def startup_gce_instance(instance_name, project, zone, username, machine_type, image, public_key, disk_name=None): """ For now, jclouds is broken for GCE and we will have static sl...
Creates EC2 Instance and saves it state in a local json file def _create_server_ec2(region, access_key_id, secret_access_key, disk_name, disk_size, ami, key_pair, ...
Creates Rackspace Instance and saves it state in a local json file def _create_server_rackspace(region, access_key_id, secret_access_key, disk_name, disk_size, ami, ...
cuisine dir_attribs doesn't do sudo, so we implement our own Updates the mode/owner/group for the given remote directory. def dir_attribs(location, mode=None, owner=None, group=None, recursive=False, use_sudo=False): """ cuisine dir_attribs doesn't do sudo, so we implement our own U...
disables selinux def disable_selinux(): """ disables selinux """ if contains(filename='/etc/selinux/config', text='SELINUX=enforcing'): sed('/etc/selinux/config', 'SELINUX=enforcing', 'SELINUX=disabled', use_sudo=True) if contains(filename='/etc/selinux/config', ...
destroys an ebs volume def destroy_ebs_volume(region, volume_id, access_key_id, secret_access_key): """ destroys an ebs volume """ conn = connect_to_ec2(region, access_key_id, secret_access_key) if ebs_volume_exists(region, volume_id, access_key_id, secret_access_key): log_yellow('destroying EBS v...
terminates the instance def destroy_ec2(region, instance_id, access_key_id, secret_access_key): """ terminates the instance """ conn = connect_to_ec2(region, access_key_id, secret_access_key) data = get_ec2_info(instance_id=instance_id, region=region, access...
terminates the instance def destroy_rackspace(region, instance_id, access_key_id, secret_access_key): """ terminates the instance """ nova = connect_to_rackspace(region, access_key_id, secret_access_key) server = nova.servers.get(instance_id)...
shutdown of an existing EC2 instance def down_ec2(instance_id, region, access_key_id, secret_access_key): """ shutdown of an existing EC2 instance """ conn = connect_to_ec2(region, access_key_id, secret_access_key) # get the instance_id from the state file, and stop the instance instance = conn.stop_in...
finds out if a ebs volume exists def ebs_volume_exists(region, volume_id, access_key_id, secret_access_key): """ finds out if a ebs volume exists """ conn = connect_to_ec2(region, access_key_id, secret_access_key) for vol in conn.get_all_volumes(): if vol.id == volume_id: return True
configures marathon to start with authentication def enable_marathon_basic_authentication(principal, password): """ configures marathon to start with authentication """ upstart_file = '/etc/init/marathon.conf' with hide('running', 'stdout'): sudo('echo -n "{}" > /etc/marathon-mesos.credentials'.for...
enables and adds a new authorized principal def enable_mesos_basic_authentication(principal, password): """ enables and adds a new authorized principal """ restart = False secrets_file = '/etc/mesos/secrets' secrets_entry = '%s %s' % (principal, password) if not file_contains(filename=secrets_file,...
Updates the mode/owner/group for the remote file at the given location. def file_attribs(location, mode=None, owner=None, group=None, sudo=False): """Updates the mode/owner/group for the remote file at the given location.""" return dir_attribs(location, mode, owner, group, False, sudo)
queries EC2 for details about a particular instance_id def get_ec2_info(instance_id, region, access_key_id, secret_access_key, username): """ queries EC2 for details about a particular instance_id """ conn = connect_to_ec2(region, access_k...
returns an ipaddress for a rackspace instance def get_ip_address_from_rackspace_server(server_id): """ returns an ipaddress for a rackspace instance """ nova = connect_to_rackspace() server = nova.servers.get(server_id) # the server was assigned IPv4 and IPv6 addresses, locate the IPv4 address ...
queries Rackspace for details about a particular server id def get_rackspace_info(server_id, region, access_key_id, secret_access_key, username): """ queries Rackspace for details about a particular server id """ no...
installs oracle java def install_oracle_java(distribution, java_version): """ installs oracle java """ if 'ubuntu' in distribution: accept_oracle_license = ('echo ' 'oracle-java' + java_version + 'installer ' 'shared/accepted-oracle-lice...
install mesos (all of it) on a single node def install_mesos_single_box_mode(distribution): """ install mesos (all of it) on a single node""" if 'ubuntu' in distribution: log_green('adding mesosphere apt-key') apt_add_key(keyid='E56151BF') os = lsb_release() apt_string = 'deb ...
inserts a line in the middle of a file def insert_line_in_file_after_regex(path, line, after_regex, use_sudo=False): """ inserts a line in the middle of a file """ tmpfile = str(uuid.uuid4()) get_file(path, tmpfile, use_sudo=use_sudo) with open(tmpfile) as f: original = f.read() if line n...
instals a python module using pip def install_python_module(name): """ instals a python module using pip """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=False, capture=True): run('pip --quiet install %s' % name)
instals a python module using pip def install_python_module_locally(name): """ instals a python module using pip """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=False, capture=True): local('pip --quiet install %s' % name)
install a particular gem def install_system_gem(gem): """ install a particular gem """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=False, capture=True): sudo("gem install %s --no-rdoc --no-ri" % gem)
checks if vagrant plugin is installed def is_vagrant_plugin_installed(plugin, use_sudo=False): """ checks if vagrant plugin is installed """ cmd = 'vagrant plugin list' if use_sudo: results = sudo(cmd) else: results = run(cmd) installed_plugins = [] for line in results: ...
checks if a particular deb package is installed def is_deb_package_installed(pkg): """ checks if a particular deb package is installed """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): result = sudo('dpkg-query -l "%s" | grep -q ^.i' %...
checks if ssh port is open def is_ssh_available(host, port=22): """ checks if ssh port is open """ s = socket.socket() try: s.connect((host, port)) return True except: return False
returns /etc/os-release in a dictionary def os_release(username, ip_address): """ returns /etc/os-release in a dictionary """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): _os_release = {} with settings(host_string=username + '@...
loads the state from a local data.json file def load_state_from_disk(): """ loads the state from a local data.json file """ if is_there_state(): with open('data.json', 'r') as f: data = json.load(f) return data else: return False
outputs information about our EC2 instance def print_ec2_info(region, instance_id, access_key_id, secret_access_key, username): """ outputs information about our EC2 instance """ data = get_ec2_info(instance_id=instance_id, ...
outputs information about our Rackspace instance def print_gce_info(zone, project, instance_name, data): """ outputs information about our Rackspace instance """ try: instance_info = _get_gce_compute().instances().get( project=project, zone=zone, instance=instance_na...
outputs information about our Rackspace instance def print_rackspace_info(region, instance_id, access_key_id, secret_access_key, username): """ outputs information about our Rackspace instance """ data = get_rac...
restarts a service def restart_service(service): """ restarts a service """ with settings(hide('running', 'stdout'), warn_only=True): log_yellow('stoping service %s' % service) sudo('service %s stop' % service) log_yellow('starting service %s' % service) sudo('service %s start'...
syncs the src code to the remote box def rsync(): """ syncs the src code to the remote box """ log_green('syncing code to remote box...') data = load_state_from_disk() if 'SOURCE_PATH' in os.environ: with lcd(os.environ['SOURCE_PATH']): local("rsync -a " "--info=p...
queries EC2 for details about a particular instance_id and stores those details locally def save_ec2_state_locally(instance_id, region, username, access_key_id, secret_access_key): """ queries EC2 fo...
opens a ssh shell to the host def ssh_session(key_filename, username, ip_address, *cli): """ opens a ssh shell to the host """ local('ssh -t -i %s %s@%s %s' % (key_filename, username, ip_ad...
boots an existing ec2_instance def up_ec2(region, access_key_id, secret_access_key, instance_id, username): """ boots an existing ec2_instance """ conn = connect_to_ec2(region, access_key_id, secret_access_key) # boot the ec2 instance instance = conn.start_i...
probes the ssh port and waits until it is available def wait_for_ssh(host, port=22, timeout=600): """ probes the ssh port and waits until it is available """ log_yellow('waiting for ssh...') for iteration in xrange(1, timeout): #noqa sleep(1) if is_ssh_available(host, port): ret...
Renvoi les éléments graphiques d'un utilisateur. :param user: Dictionnaire d'infos de l'utilisateur :return QPixmap,QLabel: Image et nom def _get_visuals(user): """ Renvoi les éléments graphiques d'un utilisateur. :param user: Dictionnaire d'infos de l'utilisateur :return QPixmap,QLabel: Imag...
save a directory to a certain alias/nickname def saveDirectory(alias): """save a directory to a certain alias/nickname""" if not settings.platformCompatible(): return False dataFile = open(settings.getDataFile(), "wb") currentDirectory = os.path.abspath(".") directory = {alias : currentDirectory} pickle.dump(d...
go to a saved directory def goToDirectory(alias): """go to a saved directory""" if not settings.platformCompatible(): return False data = pickle.load(open(settings.getDataFile(), "rb")) try: data[alias] except KeyError: speech.fail("Sorry, it doesn't look like you have saved " + alias + " yet.") speech.fa...
List model instances. Currently this gets *everything* and iterates through all possible pages in the API. This may be unsuitable for production environments with huge databases, so finer grained page support should likely be added at some point. Args: filters (dict...
Get the model instance with a given id. Args: id (int or str): The primary identifier (e.g., pk or UUID) for the task instance to get. Returns: :class:`saltant.models.resource.Model`: A :class:`saltant.models.resource.Model` subclass ...
Validates that a request was successful. Args: response_text (str): The response body of the request. request_url (str): The URL the request was made at. status_code (int): The status code of the response. expected_status_code (int): The expected status code of t...
Sync this model with latest data on the saltant server. Note that in addition to returning the updated object, it also updates the existing object. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: This task instance ... instance after syncing. ...
Wait until a task instance with the given UUID is finished. Args: refresh_period (int, optional): How many seconds to wait before checking the task's status. Defaults to 5 seconds. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstan...
Create a task instance. Args: task_type_id (int): The ID of the task type to base the task instance on. task_queue_id (int): The ID of the task queue to run the job on. arguments (dict, optional): The arguments to give the task ...
Clone the task instance with given UUID. Args: uuid (str): The UUID of the task instance to clone. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: A task instance model instance representing the task instance created due to ...
Terminate the task instance with given UUID. Args: uuid (str): The UUID of the task instance to terminate. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: A task instance model instance representing the task instance that wa...
Wait until a task instance with the given UUID is finished. Args: uuid (str): The UUID of the task instance to wait for. refresh_period (float, optional): How many seconds to wait in between checking the task's status. Defaults to 5 seconds. Retu...
Convert response data to a task instance model. Args: response_data (dict): The data from the request's response. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: A task instance model instance representing the task instance ...
I expect that there will only be one hit pr gene, but if there are more, I assume that the sequence of the hits are the same in the res file and the aln file. def kma(inputfile_1, out_path, databases, db_path_kma, min_cov=0.6, threshold=0.9, kma_path="cge/kma/kma", sample_name="", ...
Ensure all column names are unique identifiers. def _ids_and_column_names(names, force_lower_case=False): """Ensure all column names are unique identifiers.""" fixed = OrderedDict() for name in names: identifier = RowWrapper._make_identifier(name) if force_lower_case: ...
Attempt to convert string into a valid identifier by replacing invalid characters with "_"s, and prefixing with "a_" if necessary. def _make_identifier(string): """Attempt to convert string into a valid identifier by replacing invalid characters with "_"s, and prefixing with "a_" if necessary."...
Increment (or add) numeric suffix to identifier. def _increment_numeric_suffix(s): """Increment (or add) numeric suffix to identifier.""" if re.match(r".*\d+$", s): return re.sub(r"\d+$", lambda n: str(int(n.group(0)) + 1), s) return s + "_2"
Return row tuple for row. def wrap(self, row: Union[Mapping[str, Any], Sequence[Any]]): """Return row tuple for row.""" return ( self.dataclass( **{ ident: row[column_name] for ident, column_name in self.ids_and_column_names.items() ...
Return row tuple for each row in rows. def wrap_all(self, rows: Iterable[Union[Mapping[str, Any], Sequence[Any]]]): """Return row tuple for each row in rows.""" return (self.wrap(r) for r in rows)
Add custom error handlers for PyMacaronCoreExceptions to the app def add_error_handlers(app): """Add custom error handlers for PyMacaronCoreExceptions to the app""" def handle_validation_error(error): response = jsonify({'message': str(error)}) response.status_code = error.status_code ...
List all backends for a particular service and version. def list_backends(self, service_id, version_number): """List all backends for a particular service and version.""" content = self._fetch("/service/%s/version/%d/backend" % (service_id, version_number)) return map(lambda x: FastlyBackend(self, x), content)
Create a backend for a particular service and version. def create_backend(self, service_id, version_number, name, address, use_ssl=False, port=80, connect_timeout=1000, first_byte_timeout=15000, between_bytes_timeout=10000, error_threshold=0, max_conn=20, weight=100, auto_loadbalance=False...
Get the backend for a particular service and version. def get_backend(self, service_id, version_number, name): """Get the backend for a particular service and version.""" content = self._fetch("/service/%s/version/%d/backend/%s" % (service_id, version_number, name)) return FastlyBackend(self, content)