Search is not available for this dataset
text
stringlengths
75
104k
def validate_netmask(s): """Validate that a dotted-quad ip address is a valid netmask. >>> validate_netmask('0.0.0.0') True >>> validate_netmask('128.0.0.0') True >>> validate_netmask('255.0.0.0') True >>> validate_netmask('255.255.255.255') True >>> validate_netmask(BROADCAST)...
def validate_subnet(s): """Validate a dotted-quad ip address including a netmask. The string is considered a valid dotted-quad address with netmask if it consists of one to four octets (0-255) seperated by periods (.) followed by a forward slash (/) and a subnet bitmask which is expressed in dotted...
def ip2long(ip): """Convert a dotted-quad ip address to a network byte order 32-bit integer. >>> ip2long('127.0.0.1') 2130706433 >>> ip2long('127.1') 2130706433 >>> ip2long('127') 2130706432 >>> ip2long('127.0.0.256') is None True :param ip: Dotted-quad ip address (eg. '1...
def ip2network(ip): """Convert a dotted-quad ip to base network number. This differs from :func:`ip2long` in that partial addresses as treated as all network instead of network plus host (eg. '127.1' expands to '127.1.0.0') :param ip: dotted-quad ip address (eg. ‘127.0.0.1’). :type ip: str ...
def long2ip(l): """Convert a network byte order 32-bit integer to a dotted quad ip address. >>> long2ip(2130706433) '127.0.0.1' >>> long2ip(MIN_IP) '0.0.0.0' >>> long2ip(MAX_IP) '255.255.255.255' >>> long2ip(None) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call l...
def cidr2block(cidr): """Convert a CIDR notation ip address into a tuple containing the network block start and end addresses. >>> cidr2block('127.0.0.1/32') ('127.0.0.1', '127.0.0.1') >>> cidr2block('127/8') ('127.0.0.0', '127.255.255.255') >>> cidr2block('127.0.1/16') ('127.0.0.0', '...
def subnet2block(subnet): """Convert a dotted-quad ip address including a netmask into a tuple containing the network block start and end addresses. >>> subnet2block('127.0.0.1/255.255.255.255') ('127.0.0.1', '127.0.0.1') >>> subnet2block('127/255') ('127.0.0.0', '127.255.255.255') >>> sub...
def _block_from_ip_and_prefix(ip, prefix): """Create a tuple of (start, end) dotted-quad addresses from the given ip address and prefix length. :param ip: Ip address in block :type ip: long :param prefix: Prefix size for block :type prefix: int :returns: Tuple of block (start, end) """ ...
def download_shared_files(job, samples, config): """ Downloads files shared by all samples in the pipeline :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs :param list[list] samples: A nested list of sample...
def reference_preprocessing(job, samples, config): """ Spawn the jobs that create index and dict file for reference :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs :param list[list] samples: A nested list ...
def download_sample(job, sample, config): """ Download sample and store sample specific attributes :param JobFunctionWrappingJob job: passed automatically by Toil :param list sample: Contains uuid, normal URL, and tumor URL :param Namespace config: Argparse Namespace object containing argument inpu...
def index_bams(job, config): """ Convenience job for handling bam indexing to make the workflow declaration cleaner :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs """ job.fileStore.logToMaster('Indexe...
def preprocessing_declaration(job, config): """ Declare jobs related to preprocessing :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs """ if config.preprocessing: job.fileStore.logToMaster('Ran...
def static_workflow_declaration(job, config, normal_bam, normal_bai, tumor_bam, tumor_bai): """ Statically declare workflow so sections can be modularly repurposed :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inpu...
def consolidate_output(job, config, mutect, pindel, muse): """ Combine the contents of separate tarball outputs into one via streaming :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs :param str mutect: MuT...
def parse_manifest(path_to_manifest): """ Parses samples, specified in either a manifest or listed with --samples :param str path_to_manifest: Path to configuration file :return: Samples and their attributes as defined in the manifest :rtype: list[list] """ samples = [] with open(path_t...
def main(): """ Computational Genomics Lab, Genomics Institute, UC Santa Cruz Toil exome pipeline Perform variant / indel analysis given a pair of tumor/normal BAM files. Samples are optionally preprocessed (indel realignment and base quality score recalibration) The output of this pipeline is ...
def download_reference_files(job, inputs, samples): """ Downloads shared files that are used by all samples for alignment, or generates them if they were not provided. :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace inputs: Input arguments (see main) :param list[lis...
def download_sample_and_align(job, sample, inputs, ids): """ Downloads the sample and runs BWA-kit :param JobFunctionWrappingJob job: Passed by Toil automatically :param tuple(str, list) sample: UUID and URLS for sample :param Namespace inputs: Contains input arguments :param dict ids: FileStor...
def parse_manifest(manifest_path): """ Parse manifest file :param str manifest_path: Path to manifest file :return: samples :rtype: list[str, list] """ samples = [] with open(manifest_path, 'r') as f: for line in f: if not line.isspace() and not line.startswith('#'):...
def main(): """ Computational Genomics Lab, Genomics Institute, UC Santa Cruz Toil BWA pipeline Alignment of fastq reads via BWA-kit General usage: 1. Type "toil-bwa generate" to create an editable manifest and config in the current working directory. 2. Parameterize the pipeline by editin...
def _address2long(address): """ Convert an address string to a long. """ parsed = ipv4.ip2long(address) if parsed is None: parsed = ipv6.ip2long(address) return parsed
def index(self, item): """ Return the 0-based position of `item` in this IpRange. >>> r = IpRange('127.0.0.1', '127.255.255.255') >>> r.index('127.0.0.1') 0 >>> r.index('127.255.255.255') 16777214 >>> r.index('10.0.0.1') Traceback (most recent ca...
def _detach_process(): """ Detach daemon process. Forks the current process into a parent and a detached child. The child process resides in its own process group, has no controlling terminal attached and is cleaned up by the init process. Returns ``True`` for the parent and ``False`` for the ...
def _block(predicate, timeout): """ Block until a predicate becomes true. ``predicate`` is a function taking no arguments. The call to ``_block`` blocks until ``predicate`` returns a true value. This is done by polling ``predicate``. ``timeout`` is either ``True`` (block indefinitely) or a tim...
def read_pid(self): """ Return the PID of the process owning the lock. Returns ``None`` if no lock is present. """ try: with open(self._path, 'r') as f: s = f.read().strip() if not s: return None ret...
def _get_logger_file_handles(self): """ Find the file handles used by our logger's handlers. """ handles = [] for handler in self.logger.handlers: # The following code works for logging's SysLogHandler, # StreamHandler, SocketHandler, and their subclasses....
def is_running(self): """ Check if the daemon is running. """ pid = self.get_pid() if pid is None: return False # The PID file may still exist even if the daemon isn't running, # for example if it has crashed. try: os.kill(pid, 0) ...
def _get_signal_event(self, s): ''' Get the event for a signal. Checks if the signal has been enabled and raises a ``ValueError`` if not. ''' try: return self._signal_events[int(s)] except KeyError: raise ValueError('Signal {} has not been...
def send_signal(self, s): """ Send a signal to the daemon process. The signal must have been enabled using the ``signals`` parameter of :py:meth:`Service.__init__`. Otherwise, a ``ValueError`` is raised. """ self._get_signal_event(s) # Check if signal has been e...
def stop(self, block=False): """ Tell the daemon process to stop. Sends the SIGTERM signal to the daemon process, requesting it to terminate. If ``block`` is true then the call blocks until the daemon process has exited. This may take some time since the daemon ...
def kill(self, block=False): """ Kill the daemon process. Sends the SIGKILL signal to the daemon process, killing it. You probably want to try :py:meth:`stop` first. If ``block`` is true then the call blocks until the daemon process has exited. ``block`` can either be `...
def start(self, block=False): """ Start the daemon process. The daemon process is started in the background and the calling process returns. Once the daemon process is initialized it calls the :py:meth:`run` method. If ``block`` is true then the call blocks unt...
def create(opts): """Create a new environment Usage: datacats create [-bin] [--interactive] [-s NAME] [--address=IP] [--syslog] [--ckan=CKAN_VERSION] [--no-datapusher] [--site-url SITE_URL] [--no-init-db] ENVIRONMENT_DIR [PORT] Options: --address=IP Address to li...
def reset(environment, opts): """Resets a site to the default state. This will re-initialize the database and recreate the administrator account. Usage: datacats reset [-iyn] [-s NAME] [ENVIRONMENT] Options: -i --interactive Don't detach from the web container -s --site=NAME The site to rese...
def init(opts, no_install=False, quiet=False): """Initialize a purged environment or copied environment directory Usage: datacats init [-in] [--syslog] [-s NAME] [--address=IP] [--interactive] [--site-url SITE_URL] [ENVIRONMENT_DIR [PORT]] [--no-init-db] Options: --address=IP Addres...
def finish_init(environment, start_web, create_sysadmin, log_syslog=False, do_install=True, quiet=False, site_url=None, interactive=False, init_db=True): """ Common parts of create and init: Install, init db, start site, sysadmin """ if not init_db: start_web = Fa...
def save(self): """ Save profile settings into user profile directory """ config = self.profiledir + '/config' if not isdir(self.profiledir): makedirs(self.profiledir) cp = SafeConfigParser() cp.add_section('ssh') cp.set('ssh', 'private_key',...
def generate_ssh_key(self): """ Generate a new ssh private and public key """ web_command( command=["ssh-keygen", "-q", "-t", "rsa", "-N", "", "-C", "datacats generated {0}@{1}".format( getuser(), gethostname()), ...
def create(self, environment, target_name): """ Sends "create project" command to the remote server """ remote_server_command( ["ssh", environment.deploy_target, "create", target_name], environment, self, clean_up=True, )
def admin_password(self, environment, target_name, password): """ Return True if password was set successfully """ try: remote_server_command( ["ssh", environment.deploy_target, "admin_password", target_name, password], envi...
def deploy(self, environment, target_name, stream_output=None): """ Return True if deployment was successful """ try: remote_server_command( [ "rsync", "-lrv", "--safe-links", "--munge-links", "--delete", "--inplace", "-...
def num_batches(n, batch_size): """Compute the number of mini-batches required to cover a data set of size `n` using batches of size `batch_size`. Parameters ---------- n: int the number of samples in the data set batch_size: int the mini-batch size Returns ------- ...
def num_indices_generated(self): """ Get the number of indices that would be generated by this sampler. Returns ------- int, `np.inf` or `None`. An int if the number of samples is known, `np.inf` if it is infinite or `None` if the number of sample...
def in_order_indices_batch_iterator(self, batch_size): """ Create an iterator that generates in-order mini-batches of sample indices. The batches will have `batch_size` elements, with the exception of the final batch which will have less if there are not enough samples left to fi...
def shuffled_indices_batch_iterator(self, batch_size, shuffle_rng): """ Create an iterator that generates randomly shuffled mini-batches of sample indices. The batches will have `batch_size` elements, with the exception of the final batch which will have less if there are not eno...
def shuffled_indices_batch_iterator(self, batch_size, shuffle_rng): """ Create an iterator that generates randomly shuffled mini-batches of sample indices. The batches will have `batch_size` elements. The generated mini-batches indices take the form of 1D NumPy integer arrays. ...
def class_balancing_sample_weights(y): """ Compute sample weight given an array of sample classes. The weights are assigned on a per-class basis and the per-class weights are inversely proportional to their frequency. Parameters ---------- y: NumPy array, 1D dtyp...
def shuffled_indices_batch_iterator(self, batch_size, shuffle_rng): """ Create an iterator that generates randomly shuffled mini-batches of sample indices. The batches will have `batch_size` elements. The generated mini-batches indices take the form of 1D NumPy integer arrays. ...
def class_balancing_sampler(y, indices): """ Construct a `WeightedSubsetSampler` that compensates for class imbalance. Parameters ---------- y: NumPy array, 1D dtype=int sample classes, values must be 0 or positive indices: NumPy array, 1D dtype=int ...
def wait_for_service_available(container, url, timeout): """ Wait up to timeout seconds for service at host:port to start. Returns True if service becomes available, False if the container stops or raises ServiceTimeout if timeout is reached. """ start = time.time() remaining = time...
def get_data_path(filename): """ Get the path of the given file within the batchup data directory Parameters ---------- filename: str The filename to locate within the batchup data directory Returns ------- str The full path of the file """ if os.path.isabs(file...
def download(path, source_url): """ Download a file to a given path from a given URL, if it does not exist. Parameters ---------- path: str The (destination) path of the file on the local filesystem source_url: str The URL from which to download the file Returns -------...
def compute_sha256(path): """ Compute the SHA-256 hash of the file at the given path Parameters ---------- path: str The path of the file Returns ------- str The SHA-256 HEX digest """ hasher = hashlib.sha256() with open(path, 'rb') as f: # 10MB chun...
def verify_file(path, sha256): """ Verify the integrity of a file by checking its SHA-256 hash. If no digest is supplied, the digest is printed to the console. Closely follows the code in `torchvision.datasets.utils.check_integrity` Parameters ---------- path: str The path of the f...
def download_and_verify(path, source_url, sha256): """ Download a file to a given path from a given URL, if it does not exist. After downloading it, verify it integrity by checking the SHA-256 hash. Parameters ---------- path: str The (destination) path of the file on the local filesyst...
def copy_and_verify(path, source_path, sha256): """ Copy a file to a given path from a given path, if it does not exist. After copying it, verify it integrity by checking the SHA-256 hash. Parameters ---------- path: str The (destination) path of the file on the local filesystem sou...
def ckan_extension_template(name, target): """ Create ckanext-(name) in target directory. """ setupdir = '{0}/ckanext-{1}theme'.format(target, name) extdir = setupdir + '/ckanext/{0}theme'.format(name) templatedir = extdir + '/templates/' staticdir = extdir + '/static/datacats' makedirs...
def shell(environment, opts): """Run a command or interactive shell within this environment Usage: datacats [-d] [-s NAME] shell [ENVIRONMENT [COMMAND...]] Options: -d --detach Run the resulting container in the background -s --site=NAME Specify a site to run the shell on [default: primary] ENVIRON...
def paster(opts): """Run a paster command from the current directory Usage: datacats paster [-d] [-s NAME] [COMMAND...] Options: -s --site=NAME Specify a site to run this paster command on [default: primary] -d --detach Run the resulting container in the background You must be inside a datacats env...
def save_new_site(site_name, sitedir, srcdir, port, address, site_url, passwords): """ Add a site's configuration to the source dir and site dir """ cp = ConfigParser.SafeConfigParser() cp.read([srcdir + '/.datacats-environment']) section_name = 'site_' + site_name if not cp.has_se...
def save_new_environment(name, datadir, srcdir, ckan_version, deploy_target=None, always_prod=False): """ Save an environment's configuration to the source dir and data dir """ with open(datadir + '/.version', 'w') as f: f.write('2') cp = ConfigParser.SafeConfigParser() cp.read...
def find_environment_dirs(environment_name=None, data_only=False): """ :param environment_name: exising environment name, path or None to look in current or parent directories for project returns (srcdir, extension_dir, datadir) extension_dir is the name of extension directory user was in/ref...
def load_environment(srcdir, datadir=None, allow_old=False): """ Load configuration values for an environment :param srcdir: environment source directory :param datadir: environment data direcory, if None will be discovered from srcdir :param allow_old: Don't throw an exception ...
def load_site(srcdir, datadir, site_name=None): """ Load configuration values for a site. Returns (port, address, site_url, passwords) """ if site_name is None: site_name = 'primary' if not validate.valid_name(site_name): raise DatacatsError('{} is not a valid site name.'.format...
def new_environment_check(srcpath, site_name, ckan_version): """ Check if a new environment or site can be created at the given path. Returns (name, datadir, sitedir, srcdir) or raises DatacatsError """ docker.require_images() workdir, name = path.split(path.abspath(path.expanduser(srcpath))) ...
def data_complete(datadir, sitedir, get_container_name): """ Return True if the directories and containers we're expecting are present in datadir, sitedir and containers """ if any(not path.isdir(sitedir + x) for x in ('/files', '/run', '/solr')): return False if docker.is_b...
def create_directories(datadir, sitedir, srcdir=None): """ Create expected directories in datadir, sitedir and optionally srcdir """ # It's possible that the datadir already exists # (we're making a secondary site) if not path.isdir(datadir): os.makedirs(datadir, mode=0o700) try:...
def create_virtualenv(srcdir, datadir, preload_image, get_container_name): """ Populate venv from preloaded image """ try: if docker.is_boot2docker(): docker.data_only_container( get_container_name('venv'), ['/usr/lib/ckan'], ) ...
def create_source(srcdir, preload_image, datapusher=False): """ Copy ckan source, datapusher source (optional), who.ini and schema.xml from preload image into srcdir """ try: docker.web_command( command='/bin/cp -a /project/ckan /project_target/ckan', rw={srcdir: '/pr...
def start_supporting_containers(sitedir, srcdir, passwords, get_container_name, extra_containers, log_syslog=False): """ Start all supporting containers (containers required for CKAN to operate) if they aren't already running, along with some extra containers specified by the user """ if...
def stop_supporting_containers(get_container_name, extra_containers): """ Stop postgres and solr containers, along with any specified extra containers """ docker.remove_container(get_container_name('postgres')) docker.remove_container(get_container_name('solr')) for container in extra_containers...
def containers_running(get_container_name): """ Return a list of containers tracked by this environment that are running """ running = [] for n in ['web', 'postgres', 'solr', 'datapusher', 'redis']: info = docker.inspect_container(get_container_name(n)) if info and not info['State'][...
def _load_sites(self): """ Gets the names of all of the sites from the datadir and stores them in self.sites. Also returns this list. """ if not self.sites: self.sites = task.list_sites(self.datadir) return self.sites
def save_site(self, create=True): """ Save environment settings in the directory that need to be saved even when creating only a new sub-site env. """ self._load_sites() if create: self.sites.append(self.site_name) task.save_new_site(self.site_name, s...
def save(self): """ Save environment settings into environment directory, overwriting any existing configuration and discarding site config """ task.save_new_environment(self.name, self.datadir, self.target, self.ckan_version, self.deploy_target, self.always_prod)
def new(cls, path, ckan_version, site_name, **kwargs): """ Return a Environment object with settings for a new project. No directories or containers are created by this call. :params path: location for new project directory, may be relative :params ckan_version: release of CKAN ...
def load(cls, environment_name=None, site_name='primary', data_only=False, allow_old=False): """ Return an Environment object based on an existing environnment+site. :param environment_name: exising environment name, path or None to look in current or parent directories for project ...
def data_complete(self): """ Return True if all the expected datadir files are present """ return task.data_complete(self.datadir, self.sitedir, self._get_container_name)
def require_data(self): """ raise a DatacatsError if the datadir or volumes are missing or damaged """ files = task.source_missing(self.target) if files: raise DatacatsError('Missing files in source directory:\n' + '\n'.join(files)) ...
def create_directories(self, create_project_dir=True): """ Call once for new projects to create the initial project directories. """ return task.create_directories(self.datadir, self.sitedir, self.target if create_project_dir else None)
def create_virtualenv(self): """ Populate venv from preloaded image """ return task.create_virtualenv(self.target, self.datadir, self._preload_image(), self._get_container_name)
def clean_virtualenv(self): """ Empty our virtualenv so that new (or older) dependencies may be installed """ self.user_run_script( script=scripts.get_script_path('clean_virtualenv.sh'), args=[], rw_venv=True, )
def create_source(self, datapusher=True): """ Populate ckan directory from preloaded image and copy who.ini and schema.xml info conf directory """ task.create_source(self.target, self._preload_image(), datapusher)
def start_supporting_containers(self, log_syslog=False): """ Start all supporting containers (containers required for CKAN to operate) if they aren't already running. :param log_syslog: A flag to redirect all container logs to host's syslog """ log_syslog = True if ...
def create_ckan_ini(self): """ Use make-config to generate an initial development.ini file """ self.run_command( command='/scripts/run_as_user.sh /usr/lib/ckan/bin/paster make-config' ' ckan /project/development.ini', rw_project=True, ro={s...
def update_ckan_ini(self, skin=True): """ Use config-tool to update development.ini with our environment settings :param skin: use environment template skin plugin True/False """ command = [ '/usr/lib/ckan/bin/paster', '--plugin=ckan', 'config-tool', '/pr...
def create_install_template_skin(self): """ Create an example ckan extension for this environment and install it """ ckan_extension_template(self.name, self.target) self.install_package_develop('ckanext-' + self.name + 'theme')
def ckan_db_init(self, retry_seconds=DB_INIT_RETRY_SECONDS): """ Run db init to create all ckan tables :param retry_seconds: how long to retry waiting for db to start """ # XXX workaround for not knowing how long we need to wait # for postgres to be ready. fix this by ch...
def start_ckan(self, production=False, log_syslog=False, paster_reload=True, interactive=False): """ Start the apache server or paster serve :param log_syslog: A flag to redirect all container logs to host's syslog :param production: True for apache, False for paster ...
def _create_run_ini(self, port, production, output='development.ini', source='development.ini', override_site_url=True): """ Create run/development.ini in datadir with debug and site_url overridden and with correct db passwords inserted """ cp = SafeConfig...
def _run_web_container(self, port, command, address, log_syslog=False, datapusher=True, interactive=False): """ Start web container on port with command """ if is_boot2docker(): ro = {} volumes_from = self._get_container_name('venv') ...
def wait_for_web_available(self): """ Wait for the web server to become available or raise DatacatsError if it fails to start. """ try: if not wait_for_service_available( self._get_container_name('web'), self.web_address(), ...
def _choose_port(self): """ Return a port number from 5000-5999 based on the environment name to be used as a default when the user hasn't selected one. """ # instead of random let's base it on the name chosen (and the site name) return 5000 + unpack('Q', ...
def _next_port(self, port): """ Return another port from the 5000-5999 range """ port = 5000 + (port + 1) % 1000 if port == self.port: raise DatacatsError('Too many instances running') return port
def stop_ckan(self): """ Stop and remove the web container """ remove_container(self._get_container_name('web'), force=True) remove_container(self._get_container_name('datapusher'), force=True)
def _current_web_port(self): """ return just the port number for the web container, or None if not running """ info = inspect_container(self._get_container_name('web')) if info is None: return None try: if not info['State']['Running']: ...
def add_extra_container(self, container, error_on_exists=False): """ Add a container as a 'extra'. These are running containers which are not necessary for running default CKAN but are useful for certain extensions :param container: The container name to add :param error_on_exist...
def web_address(self): """ Return the url of the web server or None if not running """ port = self._current_web_port() address = self.address or '127.0.0.1' if port is None: return None return 'http://{0}:{1}/'.format( address if address an...
def create_admin_set_password(self, password): """ create 'admin' account with given password """ with open(self.sitedir + '/run/admin.json', 'w') as out: json.dump({ 'name': 'admin', 'email': 'none', 'password': password, ...