Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def externalHostname(hosts): hostname = hosts[0][0] if hostname in localHostnames and len(hosts) > 1: hostname = socket.getfqdn().split(".")[0] try: socket.getaddrinfo(hostname, None) except socket.gaierror: raise ...
[ "Ensure external hostname is routable." ]
Please provide a description of the function:def getHosts(filename=None, hostlist=None): if filename: return getHostsFromFile(filename) elif hostlist: return getHostsFromList(hostlist) elif getEnv() == "SLURM": return getHostsFromSLURM() elif getEnv() == "PBS": retur...
[ "Return a list of hosts depending on the environment" ]
Please provide a description of the function:def getHostsFromFile(filename): valid_hostname = r"^[^ /\t=\n]+" workers = r"\d+" hostname_re = re.compile(valid_hostname) worker_re = re.compile(workers) hosts = [] with open(filename) as f: for line in f: # check to see if i...
[ "Parse a file to return a list of hosts." ]
Please provide a description of the function:def getHostsFromList(hostlist): # check to see if it is a SLURM grouping instead of a # regular list of hosts if any(re.search('[\[\]]', x) for x in hostlist): return parseSLURM(str(hostlist)) # Counter would be more efficient but: # 1. Won'...
[ "Return the hosts from the command line" ]
Please provide a description of the function:def parseSLURM(string): # Use scontrol utility to get the hosts list import subprocess, os hostsstr = subprocess.check_output(["scontrol", "show", "hostnames", string]) if sys.version_info.major > 2: hostsstr = hostsstr.decode() # Split using...
[ "Return a host list from a SLURM string" ]
Please provide a description of the function:def getHostsFromPBS(): # See above comment about Counter with open(os.environ["PBS_NODEFILE"], 'r') as hosts: hostlist = groupTogether(hosts.read().split()) retVal = [] for key, group in groupby(hostlist): retVal.append((key, ...
[ "Return a host list in a PBS environment" ]
Please provide a description of the function:def getHostsFromSGE(): with open(os.environ["PE_HOSTFILE"], 'r') as hosts: return [(host.split()[0], int(host.split()[1])) for host in hosts]
[ "Return a host list in a SGE environment" ]
Please provide a description of the function:def getWorkerQte(hosts): if "SLURM_NTASKS" in os.environ: return int(os.environ["SLURM_NTASKS"]) elif "PBS_NP" in os.environ: return int(os.environ["PBS_NP"]) elif "NSLOTS" in os.environ: return int(os.environ["NSLOTS"]) else: ...
[ "Return the number of workers to launch depending on the environment" ]
Please provide a description of the function:def functionFactory(in_code, name, defaults, globals_, imports): def generatedFunction(): pass generatedFunction.__code__ = marshal.loads(in_code) generatedFunction.__name__ = name generatedFunction.__defaults = defaults generatedFunction.__g...
[ "Creates a function at runtime using binary compiled inCode" ]
Please provide a description of the function:def makeLambdaPicklable(lambda_function): if isinstance(lambda_function, type(lambda: None)) and lambda_function.__name__ == '<lambda>': def __reduce_ex__(proto): # TODO: argdefs, closure return unpickleLambda, (mars...
[ "Take input lambda function l and makes it picklable." ]
Please provide a description of the function:def getFunction(self): return functionFactory( self.code, self.name, self.defaults, self.globals, self.imports, )
[ "Called by remote workers. Useful to populate main module globals()\n for interactive shells. Retrieves the serialized function." ]
Please provide a description of the function:def writeFile(self, directory=None): if directory: # If a directory was specified full_path = os.path.join(directory, self.filename) with open(full_path, 'wb') as f: f.write(pickle.loads(self.data).read()) ...
[ "Writes back the file to a temporary path (optionaly specified)" ]
Please provide a description of the function:def addConnector(self, wire1, wire2): if wire1 == wire2: return if wire1 > wire2: wire1, wire2 = wire2, wire1 try: last_level = self[-1] except IndexError: # Empty netw...
[ "Add a connector between wire1 and wire2 in the network." ]
Please provide a description of the function:def sort(self, values): for level in self: for wire1, wire2 in level: if values[wire1] > values[wire2]: values[wire1], values[wire2] = values[wire2], values[wire1]
[ "Sort the values in-place based on the connectors in the network." ]
Please provide a description of the function:def assess(self, cases=None): if cases is None: cases = product(range(2), repeat=self.dimension) misses = 0 ordered = [[0]*(self.dimension-i) + [1]*i for i in range(self.dimension+1)] for sequence in cases: ...
[ "Try to sort the **cases** using the network, return the number of\n misses. If **cases** is None, test all possible cases according to\n the network dimensionality.\n " ]
Please provide a description of the function:def draw(self): str_wires = [["-"]*7 * self.depth] str_wires[0][0] = "0" str_wires[0][1] = " o" str_spaces = [] for i in range(1, self.dimension): str_wires.append(["-"]*7 * self.depth) str_spaces.appe...
[ "Return an ASCII representation of the network." ]
Please provide a description of the function:def getWorkersName(data): names = [fichier for fichier in data.keys()] names.sort() try: names.remove("broker") except ValueError: pass return names
[ "Returns the list of the names of the workers sorted alphabetically" ]
Please provide a description of the function:def importData(directory): dataTask = OrderedDict() dataQueue = OrderedDict() for fichier in sorted(os.listdir(directory)): try: with open("{directory}/{fichier}".format(**locals()), 'rb') as f: fileName, fileType = fichie...
[ "Parse the input files and return two dictionnaries" ]
Please provide a description of the function:def getTimes(dataTasks): global begin_time start_time, end_time = float('inf'), 0 for fichier, vals in dataTask.items(): try: if hasattr(vals, 'values'): tmp_start_time = min([a['start_time'] for a in vals.values()])[0] ...
[ "Get the start time and the end time of data in milliseconds" ]
Please provide a description of the function:def WorkersDensity(dataTasks): start_time, end_time = getTimes(dataTasks) graphdata = [] for name in getWorkersName(dataTasks): vals = dataTasks[name] if hasattr(vals, 'values'): # Data from worker workerdata = [] ...
[ "Return the worker density data for the graph." ]
Please provide a description of the function:def plotDensity(dataTask, filename): #def format_worker(x, pos=None): # # #workers = filter (lambda a: a[:6] != "broker", dataTask.keys()) # workers = [a for a in dataTask.keys() if a[:6] != "broker"] # return workers[x] def format...
[ "Plot the worker density graph", "Formats the worker name", "Formats the time" ]
Please provide a description of the function:def plotBrokerQueue(dataTask, filename): print("Plotting broker queue length for {0}.".format(filename)) plt.figure() # Queue length plt.subplot(211) for fichier, vals in dataTask.items(): if type(vals) == list: timestamps = list...
[ "Generates the broker queue length graphic." ]
Please provide a description of the function:def getWorkerInfo(dataTask): workertime = [] workertasks = [] for fichier, vals in dataTask.items(): if hasattr(vals, 'values'): #workers_names.append(fichier) # Data from worker totaltime = sum([a['executionTime']...
[ "Returns the total execution time and task quantity by worker" ]
Please provide a description of the function:def timelines(fig, y, xstart, xstop, color='b'): fig.hlines(y, xstart, xstop, color, lw=4) fig.vlines(xstart, y+0.03, y-0.03, color, lw=2) fig.vlines(xstop, y+0.03, y-0.03, color, lw=2)
[ "Plot timelines at y from xstart to xstop with given color." ]
Please provide a description of the function:def plotTimeline(dataTask, filename): fig = plt.figure() ax = fig.gca() worker_names = [x for x in dataTask.keys() if "broker" not in x] min_time = getMinimumTime(dataTask) ystep = 1. / (len(worker_names) + 1) y = 0 for worker, vals in da...
[ "Build a timeline" ]
Please provide a description of the function:def Advertise(port, stype="SCOOP", sname="Broker", advertisername="Broker", location=""): scoop.logger.info("Launching advertiser...") service = minusconf.Service(stype, port, sname, location) advertiser = minusconf.ThreadAdvertiser([service], ...
[ "\n stype = always SCOOP\n port = comma separated ports\n sname = broker unique name\n location = routable location (ip or dns)\n " ]
Please provide a description of the function:def setWorker(self, *args, **kwargs): try: la = self.LAUNCHING_ARGUMENTS(*args, **kwargs) except TypeError as e: scoop.logger.error(("addWorker failed to convert args %s and kwargs %s " "to namedtup...
[ "Add a worker assignation\n Arguments and order to pass are defined in LAUNCHING_ARGUMENTS\n Using named args is advised.\n " ]
Please provide a description of the function:def _WorkerCommand_environment(self): worker = self.workersArguments c = [] if worker.prolog: c.extend([ "source", worker.prolog, "&&", ]) if worker.pythonPath an...
[ "Return list of shell commands to prepare the environment for\n bootstrap." ]
Please provide a description of the function:def _WorkerCommand_launcher(self): return [ self.workersArguments.pythonExecutable, '-m', 'scoop.launch.__main__', str(self.workerAmount), str(self.workersArguments.verbose), ]
[ "Return list commands to start the bootstrap process" ]
Please provide a description of the function:def _WorkerCommand_options(self): worker = self.workersArguments c = [] # If broker is on localhost if self.hostname == worker.brokerHostname: broker = "127.0.0.1" else: broker = worker.brokerHostname ...
[ "Return list of options for bootstrap" ]
Please provide a description of the function:def _WorkerCommand_executable(self): worker = self.workersArguments c = [] if worker.executable: c.append(worker.executable) # This trick is used to parse correctly quotes # (ie. myScript.py 'arg1 "arg2" arg3') ...
[ "Return executable and any options to be executed by bootstrap" ]
Please provide a description of the function:def _getWorkerCommandList(self): c = [] c.extend(self._WorkerCommand_environment()) c.extend(self._WorkerCommand_launcher()) c.extend(self._WorkerCommand_options()) c.extend(self._WorkerCommand_executable()) return c
[ "Generate the workerCommand as list" ]
Please provide a description of the function:def launch(self, tunnelPorts=None): if self.isLocal(): # Launching local workers c = self._getWorkerCommandList() self.subprocesses.append(subprocess.Popen(c)) else: # Launching remotely BAS...
[ "Launch every worker assigned on this host." ]
Please provide a description of the function:def close(self): # Ensure everything is cleaned up on exit scoop.logger.debug('Closing workers on {0}.'.format(self)) # Terminate subprocesses for process in self.subprocesses: try: process.terminate() ...
[ "Connection(s) cleanup." ]
Please provide a description of the function:def _switch(self, future): scoop._control.current = self assert self.greenlet is not None, ("No greenlet to switch to:" "\n{0}".format(self.__dict__)) return self.greenlet.switch(future)
[ "Switch greenlet." ]
Please provide a description of the function:def cancel(self): if self in scoop._control.execQueue.movable: self.exceptionValue = CancelledError() scoop._control.futureDict[self.id]._delete() scoop._control.execQueue.remove(self) return True retur...
[ "If the call is currently being executed or sent for remote\n execution, then it cannot be cancelled and the method will return\n False, otherwise the call will be cancelled and the method will\n return True." ]
Please provide a description of the function:def done(self): # Flush the current future in the local buffer (potential deadlock # otherwise) try: scoop._control.execQueue.remove(self) scoop._control.execQueue.socket.sendFuture(self) except ValueError as e...
[ "Returns True if the call was successfully cancelled or finished\n running, False otherwise. This function updates the executionQueue\n so it receives all the awaiting message." ]
Please provide a description of the function:def result(self, timeout=None): if not self._ended(): return scoop.futures._join(self) if self.exceptionValue is not None: raise self.exceptionValue return self.resultValue
[ "Return the value returned by the call. If the call hasn't yet\n completed then this method will wait up to ''timeout'' seconds. More\n information in the :doc:`usage` page. If the call hasn't completed in\n timeout seconds then a TimeoutError will be raised. If timeout is not\n specifie...
Please provide a description of the function:def add_done_callback(self, callable_, inCallbackType=CallbackType.standard, inCallbackGroup=None): self.callback.append(callbackEntry(callable_, inCallbackType, ...
[ "Attach a callable to the future that will be called when the future\n is cancelled or finishes running. Callable will be called with the\n future as its only argument.\n\n Added callables are called in the order that they were added and are\n always called in a thread belonging to the p...
Please provide a description of the function:def append(self, future): if future._ended() and future.index is None: self.inprogress.add(future) elif future._ended() and future.index is not None: self.ready.append(future) elif future.greenlet is not None: ...
[ "Append a future to the queue." ]
Please provide a description of the function:def askForPreviousFutures(self): # Don't request it too often (otherwise it ping-pongs because) # the broker answer triggers the _poll of pop() if time.time() < self.lastStatus + POLLING_TIME / 1000: return self.lastStatus...
[ "Request a status for every future to the broker." ]
Please provide a description of the function:def pop(self): self.updateQueue() # If our buffer is underflowing, request more Futures if self.timelen(self) < self.lowwatermark: self.requestFuture() # If an unmovable Future is ready to be executed, return it ...
[ "Pop the next future from the queue;\n in progress futures have priority over those that have not yet started;\n higher level futures have priority over lower level ones; " ]
Please provide a description of the function:def flush(self): for elem in self: if elem.id[0] != scoop.worker: elem._delete() self.socket.sendFuture(elem) self.ready.clear() self.movable.clear()
[ "Empty the local queue and send its elements to be executed remotely.\n " ]
Please provide a description of the function:def updateQueue(self): for future in self.socket.recvFuture(): if future._ended(): # If the answer is coming back, update its entry try: thisFuture = scoop._control.futureDict[future.id] ...
[ "Process inbound communication buffer.\n Updates the local queue with elements from the broker." ]
Please provide a description of the function:def sendResult(self, future): # Greenlets cannot be pickled future.greenlet = None assert future._ended(), "The results are not valid" self.socket.sendResult(future)
[ "Send back results to broker for distribution to parent task." ]
Please provide a description of the function:def shutdown(self): self.socket.shutdown() if scoop: if scoop.DEBUG: from scoop import _debug _debug.writeWorkerDebug( scoop._control.debug_stats, scoop._control.Que...
[ "Shutdown the ressources used by the queue" ]
Please provide a description of the function:def redirectSTDOUTtoDebugFile(): import sys kwargs = {} if sys.version_info >= (3,): kwargs["encoding"] = "utf8" sys.stdout = open( os.path.join( getDebugDirectory(), "{0}.stdout".format(getDebugIdentifier()), ...
[ "Redirects the stdout and stderr of the current process to a file." ]
Please provide a description of the function:def writeWorkerDebug(debugStats, queueLength, path_suffix=""): createDirectory(path_suffix) origin_prefix = "origin-" if scoop.IS_ORIGIN else "" statsFilename = os.path.join( getDebugDirectory(), path_suffix, "{1}worker-{0}-STATS".for...
[ "Serialize the execution data using pickle and writes it into the debug\n directory." ]
Please provide a description of the function:def makeParser(): # TODO: Add environment variable (all + selection) parser = argparse.ArgumentParser( description="Starts a parallel program using SCOOP.", prog="{0} -m scoop".format(sys.executable), ) group = parser.add_mutually_exclusi...
[ "Create the SCOOP module arguments parser." ]
Please provide a description of the function:def main(): # Generate a argparse parser and parse the command-line arguments parser = makeParser() args = parser.parse_args() # Get a list of resources to launch worker(s) on hosts = utils.getHosts(args.hostfile, args.hosts) if args.n: ...
[ "Execution of the SCOOP module. Parses its command-line arguments and\n launch needed resources." ]
Please provide a description of the function:def initLogging(self): verbose_levels = { 0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG, } logging.basicConfig( level=verbose_levels[self.verbose], format="[%(asctime)-15s] %...
[ "Configures the logger." ]
Please provide a description of the function:def divideHosts(self, hosts, qty): maximumWorkers = sum(host[1] for host in hosts) # If specified amount of workers is greater than sum of each specified. if qty > maximumWorkers: index = 0 while qty > maximumWorkers:...
[ "Divide processes among hosts." ]
Please provide a description of the function:def showHostDivision(self, headless): scoop.logger.info('Worker d--istribution: ') for worker, number in self.worker_hosts: first_worker = (worker == self.worker_hosts[0][0]) scoop.logger.info(' {0}:\t{1} {2}'.format( ...
[ "Show the worker distribution over the hosts." ]
Please provide a description of the function:def _setWorker_args(self, origin): args = [] kwargs = { 'pythonPath': self.pythonpath, 'prolog': self.prolog, 'path': self.path, 'nice': self.nice, 'pythonExecutable': self.python_executable...
[ "Create the arguments to pass to the addWorker call.\n The returned args and kwargs must ordered/named according to the namedtuple\n in LAUNCH_HOST_CLASS.LAUNCHING_ARGUMENTS .\n\n both args and kwargs are supported for full flexibilty,\n but usage of kwargs only is strong...
Please provide a description of the function:def setWorkerInfo(self, hostname, workerAmount, origin): scoop.logger.debug('Initialising {0}{1} worker {2} [{3}].'.format( "local" if hostname in utils.localHostnames else "remote", " origin" if origin else "", self.work...
[ "Sets the worker information for the current host." ]
Please provide a description of the function:def run(self): # Launch the broker(s) for hostname, nb_brokers in self.broker_hosts: for ind in range(nb_brokers): if self.externalHostname in utils.localHostnames: self.brokers.append(localBroker( ...
[ "Launch the broker(s) and worker(s) assigned on every hosts." ]
Please provide a description of the function:def close(self): # Give time to flush data if debug was on if self.debug: time.sleep(10) # Terminate workers for host in self.workers: host.close() # Terminate the brokers for broker in self.b...
[ "Subprocess cleanup." ]
Please provide a description of the function:def addBrokerList(self, aBrokerInfoList): self.cluster_available.update(set(aBrokerInfoList)) # If we need another connection to a fellow broker # TODO: only connect to a given number for aBrokerInfo in aBrokerInfoList: s...
[ "Add a broker to the broker cluster available list.\n Connects to the added broker if needed." ]
Please provide a description of the function:def processConfig(self, worker_config): self.config['headless'] |= worker_config.get("headless", False) if self.config['headless']: # Launch discovery process if not self.discovery_thread: self.discovery_thread...
[ "Update the pool configuration with a worker configuration.\n " ]
Please provide a description of the function:def run(self): while True: if not self.task_socket.poll(-1): continue msg = self.task_socket.recv_multipart() msg_type = msg[1] if self.debug: self.stats.append((time.time(), ...
[ "Redirects messages until a shutdown message is received." ]
Please provide a description of the function:def main(self): if self.args is None: self.parse() self.log = utils.initLogging(self.verbose) # Change to the desired directory if self.args.workingDirectory: os.chdir(self.args.workingDirectory) if ...
[ "Bootstrap an arbitrary script.\n If no agruments were passed, use discovery module to search and connect\n to a broker." ]
Please provide a description of the function:def makeParser(self): self.parser = argparse.ArgumentParser(description='Starts the executable.', prog=("{0} -m scoop.bootstrap" ).format(sys.executable)) ...
[ "Generate the argparse parser object containing the bootloader\n accepted parameters\n " ]
Please provide a description of the function:def parse(self): if self.parser is None: self.makeParser() self.args = self.parser.parse_args() self.verbose = self.args.verbose
[ "Generate a argparse parser and parse the command-line arguments" ]
Please provide a description of the function:def setScoop(self): scoop.IS_RUNNING = True scoop.IS_ORIGIN = self.args.origin scoop.BROKER = BrokerInfo( self.args.brokerHostname, self.args.taskPort, self.args.metaPort, self.args.externalBrok...
[ "Setup the SCOOP constants." ]
Please provide a description of the function:def setupEnvironment(self=None): # get the module path in the Python path sys.path.append(os.path.dirname(os.path.abspath(scoop.MAIN_MODULE))) # Add the user arguments to argv sys.argv = sys.argv[:1] if self: sys....
[ "Set the environment (argv, sys.path and module import) of\n scoop.MAIN_MODULE.\n " ]
Please provide a description of the function:def run(self, globs=None): # Without this, the underneath import clashes with the top-level one global scoop if globs is None: globs = globals() # import the user module if scoop.MAIN_MODULE: globs.up...
[ "Import user module and start __main__\n passing globals() is required when subclassing in another module\n ", "Execute the user code.\n Wraps futures._startup (SCOOP initialisation) over the user module.\n Needs " ]
Please provide a description of the function:def addBrokerList(self, aBrokerInfoList): self.clusterAvailable.update(set(aBrokerInfoList)) # If we need another connection to a fellow broker # TODO: only connect to a given number for aBrokerInfo in aBrokerInfoList: se...
[ "Add a broker to the broker cluster available list.\n Connects to the added broker if needed." ]
Please provide a description of the function:def sendConnect(self, data): # Imported dynamically - Not used if only one broker if self.backend == 'ZMQ': import zmq self.context = zmq.Context() self.socket = self.context.socket(zmq.DEALER) self.soc...
[ "Send a CONNECT command to the broker\n :param data: List of other broker main socket URL" ]
Please provide a description of the function:def sendConnect(self, data): # Imported dynamically - Not used if only one broker if self.backend == 'ZMQ': import zmq self.context = zmq.Context() self.socket = self.context.socket(zmq.DEALER) if sys.v...
[ "Send a CONNECT command to the broker\n :param data: List of other broker main socket URL" ]
Please provide a description of the function:def close(self): # TODO: DRY with workerLaunch.py # Ensure everything is cleaned up on exit scoop.logger.debug('Closing broker on host {0}.'.format(self.hostname)) # Terminate subprocesses try: self.shell.terminat...
[ "Connection(s) cleanup." ]
Please provide a description of the function:def myFunc(parameter): print('Hello World from {0}!'.format(scoop.worker)) # It is possible to get a constant anywhere print(shared.getConst('myVar')[2]) # Parameters are handled as usual return parameter + 1
[ "This function will be executed on the remote host even if it was not\n available at launch." ]
Please provide a description of the function:def sendFuture(self, future): try: if shared.getConst(hash(future.callable), timeout=0): # Enforce name reference passing if already shared future.callable = SharedElementEncaps...
[ "Send a Future to be executed remotely." ]
Please provide a description of the function:def sendResult(self, future): future = copy.copy(future) # Remove the (now) extraneous elements from future class future.callable = future.args = future.kargs = future.greenlet = None if not future.sendResultBack: ...
[ "Send a terminated future back to its parent." ]
Please provide a description of the function:def shutdown(self): if self.OPEN: self.OPEN = False scoop.SHUTDOWN_REQUESTED = True self.socket.send(b"SHUTDOWN") self.socket.close() self.infoSocket.close() time.sleep(0.3)
[ "Sends a shutdown message to other workers." ]
Please provide a description of the function:def getSize(string): try: # We open the web page with urllib.request.urlopen(string, None, 1) as f: return sum(len(line) for line in f) except (urllib.error.URLError, socket.timeout) as e: return 0
[ " This functions opens a web sites and then calculate the total\n size of the page in bytes. This is for the sake of the example. Do\n not use this technique in real code as it is not a very bright way\n to do this." ]
Please provide a description of the function:def getValue(words): value = 0 for word in words: for letter in word: # shared.getConst will evaluate to the dictionary broadcasted by # the root Future value += shared.getConst('lettersValue')[letter] return value
[ "Computes the sum of the values of the words." ]
Please provide a description of the function:def _run_code(code, run_globals, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): if init_globals is not None: run_globals.update(init_globals) run_globals.update(__name__ = mod_name, ...
[ "Helper to run code in nominated namespace" ]
Please provide a description of the function:def _run_module_code(code, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): with _ModifiedArgv0(mod_fname): with _TempModule(mod_name) as temp_module: mod_globals = temp_mo...
[ "Helper to run code in new namespace with sys modified" ]
Please provide a description of the function:def _run_module_as_main(mod_name, alter_argv=True): try: if alter_argv or mod_name != "__main__": # i.e. -m switch mod_name, loader, code, fname = _get_module_details(mod_name) else: # i.e. directory or zipfile execution ...
[ "Runs the designated module in the __main__ namespace\n\n Note that the executed module will have full access to the\n __main__ namespace. If this is not desirable, the run_module()\n function should be used to run the module code in a fresh namespace.\n\n At the very least, these variables ...
Please provide a description of the function:def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False): mod_name, loader, code, fname = _get_module_details(mod_name) if run_name is None: run_name = mod_name pkg_name = mod_name.rpartition('.')[0] if alter_sys...
[ "Execute a module's code without importing it\n\n Returns the resulting top level namespace dictionary\n " ]
Please provide a description of the function:def _get_importer(path_name): cache = sys.path_importer_cache try: importer = cache[path_name] except KeyError: # Not yet cached. Flag as using the # standard machinery until we finish # checking the hooks cache[path_n...
[ "Python version of PyImport_GetImporter C API function" ]
Please provide a description of the function:def run_path(path_name, init_globals=None, run_name=None): if run_name is None: run_name = "<run_path>" importer = _get_importer(path_name) if isinstance(importer, imp.NullImporter): # Not a valid sys.path entry, so run the code directly ...
[ "Execute code located at the specified filesystem location\n\n Returns the resulting top level namespace dictionary\n\n The file path may refer directly to a Python script (i.e.\n one that could be directly executed with execfile) or else\n it may refer to a zipfile or directory containing a...
Please provide a description of the function:def maxTreeDepthDivide(rootValue, currentDepth=0, parallelLevel=2): thisRoot = shared.getConst('myTree').search(rootValue) if currentDepth >= parallelLevel: return thisRoot.maxDepth(currentDepth) else: # Base case if not any([thisRoot...
[ "Finds a tree node that represents rootValue and computes the max depth\n of this tree branch.\n This function will emit new futures until currentDepth=parallelLevel" ]
Please provide a description of the function:def insert(self, value): if not self.payload or value == self.payload: self.payload = value else: if value <= self.payload: if self.left: self.left.insert(value) else: ...
[ "Insert a value in the tree" ]
Please provide a description of the function:def maxDepth(self, currentDepth=0): if not any((self.left, self.right)): return currentDepth result = 0 for child in (self.left, self.right): if child: result = max(result, child.maxDepth(currentDepth +...
[ "Compute the depth of the longest branch of the tree" ]
Please provide a description of the function:def search(self, value): if self.payload == value: return self else: if value <= self.payload: if self.left: return self.left.search(value) else: if self.right: ...
[ "Find an element in the tree" ]
Please provide a description of the function:def createZMQSocket(self, sock_type): sock = self.ZMQcontext.socket(sock_type) sock.setsockopt(zmq.LINGER, LINGER_TIME) sock.setsockopt(zmq.IPV4ONLY, 0) # Remove message dropping sock.setsockopt(zmq.SNDHWM, 0) sock.se...
[ "Create a socket of the given sock_type and deactivate message dropping" ]
Please provide a description of the function:def _reportFutures(self): try: while True: time.sleep(scoop.TIME_BETWEEN_STATUS_REPORTS) fids = set(x.id for x in scoop._control.execQueue.movable) fids.update(set(x.id for x in scoop._control.execQ...
[ "Sends futures status updates to broker at intervals of\n scoop.TIME_BETWEEN_STATUS_REPORTS seconds. Is intended to be run by a\n separate thread." ]
Please provide a description of the function:def convertVariable(self, key, varName, varValue): if isinstance(varValue, encapsulation.FunctionEncapsulation): result = varValue.getFunction() # Update the global scope of the function to match the current module mainMo...
[ "Puts the function in the globals() of the main module." ]
Please provide a description of the function:def sendFuture(self, future): future = copy.copy(future) future.greenlet = None future.children = {} try: if shared.getConst(hash(future.callable), timeout=0): # Enforce name reference passing if already s...
[ "Send a Future to be executed remotely." ]
Please provide a description of the function:def _sendReply(self, destination, fid, *args): # Try to send the result directly to its parent self.addPeer(destination) try: self.direct_socket.send_multipart([ destination, REPLY, ] +...
[ "Send a REPLY directly to its destination. If it doesn't work, launch\n it back to the broker." ]
Please provide a description of the function:def shutdown(self): if self.ZMQcontext and not self.ZMQcontext.closed: scoop.SHUTDOWN_REQUESTED = True self.socket.send(SHUTDOWN) # pyzmq would issue an 'no module named zmqerror' on windows # with...
[ "Sends a shutdown message to other workers." ]
Please provide a description of the function:def _startup(rootFuture, *args, **kargs): import greenlet global _controller _controller = greenlet.greenlet(control.runController) try: result = _controller.switch(rootFuture, *args, **kargs) except scoop._comm.Shutdown: result = Non...
[ "Initializes the SCOOP environment.\n\n :param rootFuture: Any callable object (function or class object with *__call__*\n method); this object will be called once and allows the use of parallel\n calls inside this object.\n :param args: A tuple of positional arguments that will be passed to the...
Please provide a description of the function:def _mapFuture(callable_, *iterables): childrenList = [] for args in zip(*iterables): childrenList.append(submit(callable_, *args)) return childrenList
[ "Similar to the built-in map function, but each of its\n iteration will spawn a separate independent parallel Future that will run\n either locally or remotely as `callable(*args)`.\n\n :param callable: Any callable object (function or class object with *__call__*\n method); this object will be call...
Please provide a description of the function:def map(func, *iterables, **kwargs): # TODO: Handle timeout futures = _mapFuture(func, *iterables) return _mapGenerator(futures)
[ "map(func, *iterables)\n Equivalent to\n `map(func, \\*iterables, ...)\n <http://docs.python.org/library/functions.html#map>`_\n but *func* is executed asynchronously\n and several calls to func may be made concurrently. This non-blocking call\n returns an iterator which raises a TimeoutError if *...
Please provide a description of the function:def map_as_completed(func, *iterables, **kwargs): # TODO: Handle timeout for future in as_completed(_mapFuture(func, *iterables)): yield future.resultValue
[ "map_as_completed(func, *iterables)\n Equivalent to map, but the results are returned as soon as they are made\n available.\n\n :param func: Any picklable callable object (function or class object with\n *__call__* method); this object will be called to execute the Futures.\n The callable mus...
Please provide a description of the function:def _recursiveReduce(mapFunc, reductionFunc, scan, *iterables): if iterables: half = min(len(x) // 2 for x in iterables) data_left = [list(x)[:half] for x in iterables] data_right = [list(x)[half:] for x in iterables] else: data_l...
[ "Generates the recursive reduction tree. Used by mapReduce." ]
Please provide a description of the function:def mapScan(mapFunc, reductionFunc, *iterables, **kwargs): return submit( _recursiveReduce, mapFunc, reductionFunc, True, *iterables ).result()
[ "Exectues the :meth:`~scoop.futures.map` function and then applies a\n reduction function to its result while keeping intermediate reduction\n values. This is a blocking call.\n\n :param mapFunc: Any picklable callable object (function or class object with\n *__call__* method); this object will be c...
Please provide a description of the function:def mapReduce(mapFunc, reductionFunc, *iterables, **kwargs): return submit( _recursiveReduce, mapFunc, reductionFunc, False, *iterables ).result()
[ "Exectues the :meth:`~scoop.futures.map` function and then applies a\n reduction function to its result. The reduction function will cumulatively\n merge the results of the map function in order to get a single final value.\n This call is blocking.\n\n :param mapFunc: Any picklable callable object (func...
Please provide a description of the function:def _createFuture(func, *args, **kwargs): assert callable(func), ( "The provided func parameter is not a callable." ) if scoop.IS_ORIGIN and "SCOOP_WORKER" not in sys.modules: sys.modules["SCOOP_WORKER"] = sys.modules["__main__"] # If f...
[ "Helper function to create a future." ]