_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q28700
distVersion
train
def distVersion(): """ The distribution version identifying a published release on PyPI. """ from pkg_resources import parse_version build_number = buildNumber() parsedBaseVersion = parse_version(baseVersion) if isinstance(parsedBaseVersion, tuple): raise RuntimeError("Setuptools ver...
python
{ "resource": "" }
q28701
GlobalThrottle.throttle
train
def throttle( self, wait=True ): """ If the wait parameter is True, this method returns True after suspending the current thread as necessary to ensure that no less than the configured minimum interval passed since the most recent time an invocation of this method returned True in any th...
python
{ "resource": "" }
q28702
LocalThrottle.throttle
train
def throttle( self, wait=True ): """ If the wait parameter is True, this method returns True after suspending the current thread as necessary to ensure that no less than the configured minimum interval has passed since the last invocation of this method in the current thread returned Tru...
python
{ "resource": "" }
q28703
ParasolBatchSystem._runParasol
train
def _runParasol(self, command, autoRetry=True): """ Issues a parasol command using popen to capture the output. If the command fails then it will try pinging parasol until it gets a response. When it gets a response it will recursively call the issue parasol command, repeating this patte...
python
{ "resource": "" }
q28704
ParasolBatchSystem.issueBatchJob
train
def issueBatchJob(self, jobNode): """ Issues parasol with job commands. """ self.checkResourceRequest(jobNode.memory, jobNode.cores, jobNode.disk) MiB = 1 << 20 truncatedMemory = (old_div(jobNode.memory, MiB)) * MiB # Look for a batch for jobs with these resource...
python
{ "resource": "" }
q28705
ParasolBatchSystem.getJobIDsForResultsFile
train
def getJobIDsForResultsFile(self, resultsFile): """ Get all queued and running jobs for a results file. """ jobIDs = [] for line in self._runParasol(['-extended', 'list', 'jobs'])[1]:
python
{ "resource": "" }
q28706
ParasolBatchSystem.getIssuedBatchJobIDs
train
def getIssuedBatchJobIDs(self): """ Gets the list of jobs issued to parasol in all results files, but not including jobs created by other
python
{ "resource": "" }
q28707
ParasolBatchSystem.getRunningBatchJobIDs
train
def getRunningBatchJobIDs(self): """ Returns map of running jobIDs and the time they have been running. """ # Example lines.. # r 5410186 benedictpaten worker 1247029663 localhost # r 5410324 benedictpaten worker 1247030076 localhost runningJobs = {} issue...
python
{ "resource": "" }
q28708
ParasolBatchSystem.updatedJobWorker
train
def updatedJobWorker(self): """ We use the parasol results to update the status of jobs, adding them to the list of updated jobs. Results have the following structure.. (thanks Mark D!) int status; /* Job status - wait() return format. 0 is good. */ char *host; /*...
python
{ "resource": "" }
q28709
process_infile
train
def process_infile(f, fileStore): """ Takes an array of files or a single file and imports into the jobstore. This returns a tuple or an array of tuples replacing all previous path strings. Toil does not preserve a file's original name upon import and so the tuple keeps track of this with the form...
python
{ "resource": "" }
q28710
GCEProvisioner._readCredentials
train
def _readCredentials(self): """ Get the credentials from the file specified by GOOGLE_APPLICATION_CREDENTIALS. """ self._googleJson = os.getenv('GOOGLE_APPLICATION_CREDENTIALS') if not self._googleJson: raise RuntimeError('GOOGLE_APPLICATION_CREDENTIALS not set.') ...
python
{ "resource": "" }
q28711
GCEProvisioner.destroyCluster
train
def destroyCluster(self): """ Try a few times to terminate all of the instances in the group. """ logger.debug("Destroying cluster %s" % self.clusterName) instancesToTerminate = self._getNodesInCluster() attempts = 0 while instancesToTerminate and attempts < 3: ...
python
{ "resource": "" }
q28712
GCEProvisioner._injectWorkerFiles
train
def _injectWorkerFiles(self, node, botoExists): """ Set up the credentials on the worker. """ node.waitForNode('toil_worker', keyName=self._keyName) node.copySshKeys(self._keyName)
python
{ "resource": "" }
q28713
GCEProvisioner._getDriver
train
def _getDriver(self): """ Connect to GCE """ driverCls = get_driver(Provider.GCE) return driverCls(self._clientEmail, self._googleJson,
python
{ "resource": "" }
q28714
GCEProvisioner.ex_create_multiple_nodes
train
def ex_create_multiple_nodes( self, base_name, size, image, number, location=None, ex_network='default', ex_subnetwork=None, ex_tags=None, ex_metadata=None, ignore_errors=True, use_existing_disk=True, poll_interval=2, external_ip='ephemeral', ex_disk_type='pd-...
python
{ "resource": "" }
q28715
fetch_parent_dir
train
def fetch_parent_dir(filepath, n=1): '''Returns a parent directory, n places above the input filepath. Equivalent to something like: '/home/user/dir'.split('/')[-2] if n=2. ''' filepath = os.path.realpath(filepath)
python
{ "resource": "" }
q28716
ToilStatus.print_dot_chart
train
def print_dot_chart(self): """Print a dot output graph representing the workflow.""" print("digraph toil_graph {") print("# This graph was created from job-store: %s" % self.jobStoreName) # Make job IDs to node names map jobsToNodeNames = dict(enumerate(map(lambda job: job.jobSt...
python
{ "resource": "" }
q28717
ToilStatus.printJobLog
train
def printJobLog(self): """Takes a list of jobs, finds their log files, and prints them to the terminal.""" for job in self.jobsToReport: if job.logJobStoreFileID is not None: msg = "LOG_FILE_OF_JOB:%s LOG: =======>\n" % job with job.getLogFileHandle(self.jobSt...
python
{ "resource": "" }
q28718
ToilStatus.printJobChildren
train
def printJobChildren(self): """Takes a list of jobs, and prints their successors.""" for job in self.jobsToReport: children = "CHILDREN_OF_JOB:%s " % job for level, jobList in enumerate(job.stack):
python
{ "resource": "" }
q28719
ToilStatus.printAggregateJobStats
train
def printAggregateJobStats(self, properties, childNumber): """Prints a job's ID, log file, remaining tries, and other properties.""" for job in self.jobsToReport: lf = lambda x: "%s:%s" % (x, str(x in properties)) print("\t".join(("JOB:%s" % job, "LOG...
python
{ "resource": "" }
q28720
ToilStatus.report_on_jobs
train
def report_on_jobs(self): """ Gathers information about jobs such as its child jobs and status. :returns jobStats: Pairings of a useful category and a list of jobs which fall into it. :rtype dict: """ hasChildren = [] readyToRun = [] zombies = [] ...
python
{ "resource": "" }
q28721
ToilStatus.getPIDStatus
train
def getPIDStatus(jobStoreName): """ Determine the status of a process with a particular pid. Checks to see if a process exists or not. :return: A string indicating the status of the PID of the workflow as stored in the jobstore. :rtype: str """ try: ...
python
{ "resource": "" }
q28722
ToilStatus.getStatus
train
def getStatus(jobStoreName): """ Determine the status of a workflow. If the jobstore does not exist, this returns 'QUEUED', assuming it has not been created yet. Checks for the existence of files created in the toil.Leader.run(). In toil.Leader.run(), if a workflow completes wi...
python
{ "resource": "" }
q28723
ToilStatus.fetchRootJob
train
def fetchRootJob(self): """ Fetches the root job from the jobStore that provides context for all other jobs. Exactly the same as the jobStore.loadRootJob() function, but with a different exit message if the root job is not found (indicating the workflow ran successfully
python
{ "resource": "" }
q28724
ToilStatus.fetchUserJobs
train
def fetchUserJobs(self, jobs): """ Takes a user input array of jobs, verifies that they are in the jobStore and returns the array of jobsToReport. :param list jobs: A list of jobs to be verified. :returns jobsToReport: A list of jobs which are verified to be in the jobStore. ...
python
{ "resource": "" }
q28725
ToilStatus.traverseJobGraph
train
def traverseJobGraph(self, rootJob, jobsToReport=None, foundJobStoreIDs=None): """ Find all current jobs in the jobStore and return them as an Array. :param jobNode rootJob: The root job of the workflow. :param list jobsToReport: A list of jobNodes to be added to and returned. :...
python
{ "resource": "" }
q28726
lookupEnvVar
train
def lookupEnvVar(name, envName, defaultValue): """ Use this for looking up environment variables that control Toil and are important enough to log the result of that lookup. :param str name: the human readable name of the variable :param str envName: the name of the environment variable to lookup ...
python
{ "resource": "" }
q28727
checkDockerImageExists
train
def checkDockerImageExists(appliance): """ Attempts to check a url registryName for the existence of a docker image with a given tag. :param str appliance: The url of a docker image's registry (with a tag) of the form: 'quay.io/<repo_path>:<tag>' or '<repo_path>:<tag>'. ...
python
{ "resource": "" }
q28728
parseDockerAppliance
train
def parseDockerAppliance(appliance): """ Takes string describing a docker image and returns the parsed registry, image reference, and tag for that image. Example: "quay.io/ucsc_cgl/toil:latest" Should return: "quay.io", "ucsc_cgl/toil", "latest" If a registry is not defined, the default is: "d...
python
{ "resource": "" }
q28729
requestCheckRegularDocker
train
def requestCheckRegularDocker(origAppliance, registryName, imageName, tag): """ Checks to see if an image exists using the requests library. URL is based on the docker v2 schema described here: https://docs.docker.com/registry/spec/manifest-v2-2/ This has the following format: https://{website...
python
{ "resource": "" }
q28730
requestCheckDockerIo
train
def requestCheckDockerIo(origAppliance, imageName, tag): """ Checks docker.io to see if an image exists using the requests library. URL is based on the docker v2 schema. Requires that an access token be fetched first. :param str origAppliance: The full url of the docker image originally ...
python
{ "resource": "" }
q28731
JobGraph.restartCheckpoint
train
def restartCheckpoint(self, jobStore): """Restart a checkpoint after the total failure of jobs in its subtree. Writes the changes to the jobStore immediately. All the checkpoint's successors will be deleted, but its retry count will *not* be decreased. Returns a list with the I...
python
{ "resource": "" }
q28732
Context.absolute_name
train
def absolute_name(self, name): """ Returns the absolute form of the specified resource name. If the specified name is already absolute, that name will be returned unchanged, otherwise the given name will be prefixed with the namespace this object was configured with. Relative na...
python
{ "resource": "" }
q28733
Context.to_aws_name
train
def to_aws_name(self, name): """ Returns a transliteration of the name that safe to use for resource names on AWS. If the given name is relative, it converted to its absolute form before the transliteration. The transliteration uses two consequitive '_' to encode a single '_' and a sing...
python
{ "resource": "" }
q28734
Resource.create
train
def create(cls, jobStore, leaderPath): """ Saves the content of the file or directory at the given path to the given job store and returns a resource object representing that content for the purpose of obtaining it again at a generic, public URL. This method should be invoked on the lead...
python
{ "resource": "" }
q28735
Resource.prepareSystem
train
def prepareSystem(cls): """ Prepares this system for the downloading and lookup of resources. This method should only be invoked on a worker node. It is idempotent but not thread-safe. """ try: resourceRootDirPath = os.environ[cls.rootDirPathEnvName]
python
{ "resource": "" }
q28736
Resource.cleanSystem
train
def cleanSystem(cls): """ Removes all downloaded, localized resources """ resourceRootDirPath = os.environ[cls.rootDirPathEnvName] os.environ.pop(cls.rootDirPathEnvName) shutil.rmtree(resourceRootDirPath)
python
{ "resource": "" }
q28737
Resource.lookup
train
def lookup(cls, leaderPath): """ Returns a resource object representing a resource created from a file or directory at the given path on the leader. This method should be invoked on the worker. The given path does not need to refer to an existing file or directory on the worker, it only ...
python
{ "resource": "" }
q28738
Resource.localDirPath
train
def localDirPath(self): """ The path to the directory containing the resource on the worker. """
python
{ "resource": "" }
q28739
Resource._download
train
def _download(self, dstFile): """ Download this resource from its URL to the given file object. :type dstFile: io.BytesIO|io.FileIO """ for attempt in retry(predicate=lambda e: isinstance(e, HTTPError) and e.code == 400): with attempt:
python
{ "resource": "" }
q28740
ModuleDescriptor._check_conflict
train
def _check_conflict(cls, dirPath, name): """ Check whether the module of the given name conflicts with another module on the sys.path. :param dirPath: the directory from which the module was originally loaded :param name: the mpdule name """ old_sys_path = sys.path ...
python
{ "resource": "" }
q28741
ModuleDescriptor._getResourceClass
train
def _getResourceClass(self): """ Return the concrete subclass of Resource that's appropriate for auto-deploying this module. """ if self.fromVirtualEnv: subcls = VirtualEnvResource elif os.path.isdir(self._resourcePath):
python
{ "resource": "" }
q28742
ModuleDescriptor.localize
train
def localize(self): """ Check if this module was saved as a resource. If it was, return a new module descriptor that points to a local copy of that resource. Should only be called on a worker node. On the leader, this method returns this resource, i.e. self. :rtype: toil.resourc...
python
{ "resource": "" }
q28743
ModuleDescriptor._resourcePath
train
def _resourcePath(self): """ The path to the directory that should be used when shipping this module and its siblings around as a resource. """ if self.fromVirtualEnv: return self.dirPath elif '.' in self.name: return os.path.join(self.dirPath, sel...
python
{ "resource": "" }
q28744
fetchJobStoreFiles
train
def fetchJobStoreFiles(jobStore, options): """ Takes a list of file names as glob patterns, searches for these within a given directory, and attempts to take all of the files found and copy them into options.localFilePath. :param jobStore: A fileJobStore object. :param options.fetch: List of fi...
python
{ "resource": "" }
q28745
printContentsOfJobStore
train
def printContentsOfJobStore(jobStorePath, nameOfJob=None): """ Fetch a list of all files contained in the jobStore directory input if nameOfJob is not declared, otherwise it only prints out the names of files for that specific job for which it can find a match. Also creates a logFile containing thi...
python
{ "resource": "" }
q28746
BaseJob.disk
train
def disk(self): """ The maximum number of bytes of disk the job will require to run. """ if self._disk is not None: return self._disk elif self._config is not None:
python
{ "resource": "" }
q28747
BaseJob.memory
train
def memory(self): """ The maximum number of bytes of memory the job will require to run. """ if self._memory is not None: return self._memory elif self._config is not None:
python
{ "resource": "" }
q28748
BaseJob.cores
train
def cores(self): """ The number of CPU cores required. """ if self._cores is not None: return self._cores elif self._config is not None:
python
{ "resource": "" }
q28749
BaseJob.preemptable
train
def preemptable(self): """ Whether the job can be run on a preemptable node. """ if self._preemptable is not None: return self._preemptable elif self._config is not None: return
python
{ "resource": "" }
q28750
BaseJob._requirements
train
def _requirements(self): """ Gets a dictionary of all the object's resource requirements. Unset values are defaulted to None """ return {'memory': getattr(self, 'memory', None), 'cores': getattr(self, 'cores', None),
python
{ "resource": "" }
q28751
BaseJob._parseResource
train
def _parseResource(name, value): """ Parse a Toil job's resource requirement value and apply resource-specific type checks. If the value is a string, a binary or metric unit prefix in it will be evaluated and the corresponding integral value will be returned. :param str name: Th...
python
{ "resource": "" }
q28752
Job.addFollowOn
train
def addFollowOn(self, followOnJob): """ Adds a follow-on job, follow-on jobs will be run after the child jobs and \ their successors have been run. :param toil.job.Job followOnJob: :return: followOnJob :rtype: toil.job.Job
python
{ "resource": "" }
q28753
Job.addService
train
def addService(self, service, parentService=None): """ Add a service. The :func:`toil.job.Job.Service.start` method of the service will be called after the run method has completed but before any successors are run. The service's :func:`toil.job.Job.Service.stop` method will be ...
python
{ "resource": "" }
q28754
Job.addChildFn
train
def addChildFn(self, fn, *args, **kwargs): """ Adds a function as a child job. :param fn: Function to be run as a child job with ``*args`` and ``**kwargs`` as \ arguments to this function. See toil.job.FunctionWrappingJob for reserved \ keyword arguments used to specify resource...
python
{ "resource": "" }
q28755
Job.addFollowOnFn
train
def addFollowOnFn(self, fn, *args, **kwargs): """ Adds a function as a follow-on job. :param fn: Function to be run as a follow-on job with ``*args`` and ``**kwargs`` as \ arguments to this function. See toil.job.FunctionWrappingJob for reserved \ keyword arguments used to speci...
python
{ "resource": "" }
q28756
Job.checkNewCheckpointsAreLeafVertices
train
def checkNewCheckpointsAreLeafVertices(self): """ A checkpoint job is a job that is restarted if either it fails, or if any of \ its successors completely fails, exhausting their retries. A job is a leaf it is has no successors. A checkpoint job must be a leaf when initially ad...
python
{ "resource": "" }
q28757
Job._addPredecessor
train
def _addPredecessor(self, predecessorJob): """ Adds a predecessor job to the set of predecessor jobs. Raises a \ RuntimeError if the job is already a predecessor. """ if predecessorJob in self._directPredecessors:
python
{ "resource": "" }
q28758
Job._dfs
train
def _dfs(self, visited): """ Adds the job and all jobs reachable on a directed path from current node to the given set. """ if self not in visited:
python
{ "resource": "" }
q28759
Job._checkJobGraphAcylicDFS
train
def _checkJobGraphAcylicDFS(self, stack, visited, extraEdges): """ DFS traversal to detect cycles in augmented job graph. """ if self not in visited: visited.add(self) stack.append(self) for successor in self._children + self._followOns + extraEdges[se...
python
{ "resource": "" }
q28760
Job._getImpliedEdges
train
def _getImpliedEdges(roots): """ Gets the set of implied edges. See Job.checkJobGraphAcylic """ #Get nodes in job graph nodes = set() for root in roots: root._dfs(nodes) ##For each follow-on edge calculate the extra implied edges #Adjacency li...
python
{ "resource": "" }
q28761
Job._createEmptyJobGraphForJob
train
def _createEmptyJobGraphForJob(self, jobStore, command=None, predecessorNumber=0): """ Create an empty job for the job. """ # set _config to determine user determined default values for resource requirements self._config = jobStore.config
python
{ "resource": "" }
q28762
Job._makeJobGraphs
train
def _makeJobGraphs(self, jobGraph, jobStore): """ Creates a jobGraph for each job in the job graph, recursively. """ jobsToJobGraphs = {self:jobGraph} for successors in (self._followOns, self._children):
python
{ "resource": "" }
q28763
Job._serialiseJob
train
def _serialiseJob(self, jobStore, jobsToJobGraphs, rootJobGraph): """ Pickle a job and its jobGraph to disk. """ # Pickle the job so that its run method can be run at a later time. # Drop out the children/followOns/predecessors/services - which are # all recorded within t...
python
{ "resource": "" }
q28764
Job._serialiseServices
train
def _serialiseServices(self, jobStore, jobGraph, rootJobGraph): """ Serialises the services for a job. """ def processService(serviceJob, depth): # Extend the depth of the services if necessary if depth == len(jobGraph.services): jobGraph.services....
python
{ "resource": "" }
q28765
Job._serialiseJobGraph
train
def _serialiseJobGraph(self, jobGraph, jobStore, returnValues, firstJob): """ Pickle the graph of jobs in the jobStore. The graph is not fully serialised \ until the jobGraph itself is written to disk, this is not performed by this \ function because of the need to coordinate this operat...
python
{ "resource": "" }
q28766
Job._serialiseFirstJob
train
def _serialiseFirstJob(self, jobStore): """ Serialises the root job. Returns the wrapping job. :param toil.jobStores.abstractJobStore.AbstractJobStore jobStore: """ # Check if the workflow root is a checkpoint but not a leaf vertex. # All other job vertices in the graph...
python
{ "resource": "" }
q28767
Job._serialiseExistingJob
train
def _serialiseExistingJob(self, jobGraph, jobStore, returnValues): """ Serialise an existing job. """ self._serialiseJobGraph(jobGraph, jobStore, returnValues, False) #Drop the completed command, if not dropped already jobGraph.command = None #Merge any children (...
python
{ "resource": "" }
q28768
Job._executor
train
def _executor(self, jobGraph, stats, fileStore): """ This is the core wrapping method for running the job within a worker. It sets up the stats and logging before yielding. After completion of the body, the function will finish up the stats and logging, and starts the async update proce...
python
{ "resource": "" }
q28769
Job._runner
train
def _runner(self, jobGraph, jobStore, fileStore): """ This method actually runs the job, and serialises the next jobs. :param class jobGraph: Instance of a jobGraph object :param class jobStore: Instance of the job store :param toil.fileStore.FileStore fileStore: Instance of a C...
python
{ "resource": "" }
q28770
PromisedRequirementFunctionWrappingJob.create
train
def create(cls, userFunction, *args, **kwargs): """ Creates an encapsulated Toil job function with unfulfilled promised resource requirements. After the promises are fulfilled, a child job function is created using updated resource values. The subgraph is encapsulated to ensure that this...
python
{ "resource": "" }
q28771
PromisedRequirement.getValue
train
def getValue(self): """ Returns PromisedRequirement value """
python
{ "resource": "" }
q28772
PromisedRequirement.convertPromises
train
def convertPromises(kwargs): """ Returns True if reserved resource keyword is a Promise or PromisedRequirement instance. Converts Promise instance to PromisedRequirement. :param kwargs: function keyword arguments
python
{ "resource": "" }
q28773
getPublicIP
train
def getPublicIP(): """Get the IP that this machine uses to contact the internet. If behind a NAT, this will still be this computer's IP, and not the router's.""" try: # Try to get the internet-facing IP by attempting a connection # to a non-existent server and reading what IP was used. ...
python
{ "resource": "" }
q28774
setDefaultOptions
train
def setDefaultOptions(config): """ Set default options for builtin batch systems. This is required if a Config object is not constructed from an Options object. """ config.batchSystem = "singleMachine" config.disableAutoDeployment = False config.environment = {} config.statePollingWait =...
python
{ "resource": "" }
q28775
googleRetry
train
def googleRetry(f): """ This decorator retries the wrapped function if google throws any angry service errors. It should wrap any function that makes use of the Google Client API """ @wraps(f) def wrapper(*args, **kwargs): for attempt in retry(delays=truncExpBackoff(),
python
{ "resource": "" }
q28776
GoogleJobStore._getBlobFromURL
train
def _getBlobFromURL(cls, url, exists=False): """ Gets the blob specified by the url. caution: makes no api request. blob may not ACTUALLY exist :param urlparse.ParseResult url: the URL :param bool exists: if True, then syncs local blob object with cloud and raises exce...
python
{ "resource": "" }
q28777
mean
train
def mean(xs): """ Return the mean value of a sequence of values. >>> mean([2,4,4,4,5,5,7,9]) 5.0 >>> mean([9,10,11,7,13]) 10.0 >>> mean([1,1,10,19,19]) 10.0 >>> mean([10,10,10,10,10]) 10.0 >>> mean([1,"b"]) Traceback (most recent call last): ... ValueError: Inp...
python
{ "resource": "" }
q28778
std_dev
train
def std_dev(xs): """ Returns the standard deviation of the given iterable of numbers. From http://rosettacode.org/wiki/Standard_deviation#Python An empty list, or a list with non-numeric elements will raise a TypeError. >>> std_dev([2,4,4,4,5,5,7,9]) 2.0 >>> std_dev([9,10,11,7,13]) 2...
python
{ "resource": "" }
q28779
partition_seq
train
def partition_seq(seq, size): """ Splits a sequence into an iterable of subsequences. All subsequences are of the given size, except the last one, which may be smaller. If the input list is modified while the returned list is processed, the behavior of the program is undefined. :param seq: the list...
python
{ "resource": "" }
q28780
filter
train
def filter( names, pat ): """Return the subset of the list NAMES that match PAT""" import os, posixpath result = [ ] pat = os.path.normcase( pat ) if not pat in _cache: res = translate( pat ) if len( _cache ) >= _MAXCACHE: _cache.clear( )
python
{ "resource": "" }
q28781
AzureProvisioner._readClusterSettings
train
def _readClusterSettings(self): """ Read the current instance's meta-data to get the cluster settings. """ # get the leader metadata mdUrl = "http://169.254.169.254/metadata/instance?api-version=2017-08-01" header = {'Metadata': 'True'} request = urllib.request.Re...
python
{ "resource": "" }
q28782
AzureProvisioner.launchCluster
train
def launchCluster(self, leaderNodeType, leaderStorage, owner, **kwargs): """ Launches an Azure cluster using Ansible. A resource group is created for the cluster. All the virtual machines are created within this resource group. Cloud-config is called during vm creation to create...
python
{ "resource": "" }
q28783
AzureProvisioner._checkIfClusterExists
train
def _checkIfClusterExists(self): """ Try deleting the resource group. This will fail if it exists and raise an exception. """ ansibleArgs = { 'resgrp': self.clusterName, 'region': self._zone } try:
python
{ "resource": "" }
q28784
encrypt
train
def encrypt(message, keyPath): """ Encrypts a message given a path to a local file containing a key. :param message: The message to be encrypted. :param keyPath: A path to a file containing a 256-bit key (and nothing else). :type message: bytes :type keyPath: str :rtype: bytes A consta...
python
{ "resource": "" }
q28785
memoize
train
def memoize(f): """ A decorator that memoizes a function result based on its parameters. For example, this can be used in place of lazy initialization. If the decorating function is invoked by multiple threads, the decorated function may be called more than once with the same arguments. """ # TO...
python
{ "resource": "" }
q28786
sync_memoize
train
def sync_memoize(f): """ Like memoize, but guarantees that decorated function is only called once, even when multiple threads are calling the decorating function with multiple parameters. """ # TODO: Think about an f that is recursive memory = {} lock = Lock() @wraps(f) def new_f(*a...
python
{ "resource": "" }
q28787
less_strict_bool
train
def less_strict_bool(x): """Idempotent and None-safe version of strict_bool.""" if x is None: return False
python
{ "resource": "" }
q28788
setup
train
def setup(job, input_file_id, n, down_checkpoints): """Sets up the sort. Returns the FileID of the sorted file """ # Write the input file to the file store job.fileStore.logToMaster("Starting the merge sort") return job.addChildJobFn(down,
python
{ "resource": "" }
q28789
down
train
def down(job, input_file_id, n, down_checkpoints): """Input is a file and a range into that file to sort and an output location in which to write the sorted file. If the range is larger than a threshold N the range is divided recursively and a follow on job is then created which merges back the results....
python
{ "resource": "" }
q28790
up
train
def up(job, input_file_id_1, input_file_id_2): """Merges the two files and places them in the output. """ with job.fileStore.writeGlobalFileStream() as (fileHandle, output_id): with job.fileStore.readGlobalFileStream(input_file_id_1) as inputFileHandle1: with job.fileStore.readGlobalFile...
python
{ "resource": "" }
q28791
sort
train
def sort(in_file, out_file): """Sorts the given file. """ filehandle = open(in_file, 'r') lines = filehandle.readlines()
python
{ "resource": "" }
q28792
merge
train
def merge(filehandle_1, filehandle_2, output_filehandle): """Merges together two files maintaining sorted order. """ line2 = filehandle_2.readline() for line1 in filehandle_1.readlines(): while line2 != '' and line2 <= line1: output_filehandle.write(line2)
python
{ "resource": "" }
q28793
get_midpoint
train
def get_midpoint(file, file_start, file_end): """Finds the point in the file to split. Returns an int i such that fileStart <= i < fileEnd """ filehandle = open(file, 'r') mid_point = (file_start + file_end) / 2 assert mid_point >= file_start filehandle.seek(mid_point) line = filehandle....
python
{ "resource": "" }
q28794
FileJobStore.robust_rmtree
train
def robust_rmtree(self, path, max_retries=3): """Robustly tries to delete paths. Retries several times (with increasing delays) if an OSError occurs. If the final attempt fails, the Exception is propagated to the caller. Borrowing patterns from: https://github.com/hash...
python
{ "resource": "" }
q28795
FileJobStore._getUniqueName
train
def _getUniqueName(self, fileName, jobStoreID=None, sourceFunctionName="x"): """ Create unique file name within a jobStore directory or tmp directory. :param fileName: A file name, which can be a full path as only the basename will be used. :param jobStoreID: If given, the path ...
python
{ "resource": "" }
q28796
_fetchAzureAccountKey
train
def _fetchAzureAccountKey(accountName): """ Find the account key for a given Azure storage account. The account key is taken from the AZURE_ACCOUNT_KEY_<account> environment variable if it exists, then from plain AZURE_ACCOUNT_KEY, and then from looking in the file ~/.toilAzureCredentials. That fil...
python
{ "resource": "" }
q28797
dockerPredicate
train
def dockerPredicate(e): """ Used to ensure Docker exceptions are retried if appropriate :param e: Exception :return: True if e retriable, else False """
python
{ "resource": "" }
q28798
getContainerName
train
def getContainerName(job): """Create a random string including the job name, and return it.""" return '--'.join([str(job),
python
{ "resource": "" }
q28799
AnsibleDriver.callPlaybook
train
def callPlaybook(self, playbook, ansibleArgs, wait=True, tags=["all"]): """ Run a playbook. :param playbook: An Ansible playbook to run. :param ansibleArgs: Arguments to pass to the playbook. :param wait: Wait for the play to finish if true. :param tags: Control tags for...
python
{ "resource": "" }