code stringlengths 1 18.2k |
|---|
def get_pandas_series(self): """The function creates pandas series based on index and values""" return pandas.Series(self.values, self.index, name=self.name) |
def remove(path, force=False): ''' Remove file or directory (recursively), if it exists. On NFS file systems, if a directory contains :file:`.nfs*` temporary files (sometimes created when deleting a file), it waits for them to go away. Parameters ---------- path : ~pathlib.Path Path to remove. force : bool If True, wil... |
symlinks to directories as directories file = dir_ / file if file.is_symlink(): with suppress(FileNotFoundError): file.unlink() # Now remove all dirs, being careful of any lingering .nfs* files for dir_, _, _ in os.walk(str(path), topdown=False): # bottom-up walk dir_ = Path(dir_) with suppress(FileNotFoundError): # wa... |
def chmod(path, mode, operator='=', recursive=False): ''' Change file mode bits. When recursively chmodding a directory, executable bits in ``mode`` are ignored when applying to a regular file. E.g. ``chmod(path, mode=0o777, recursive=True)`` would apply ``mode=0o666`` to regular files. Symlinks are ignored. Parameters... |
operator == '-': mode_ = path.stat().st_mode & ~mode else: mode_ = mode if path.is_symlink(): # Do not chmod or follow symlinks return path.chmod(mode_) # then its children def chmod_children(parent, files, mode_mask, operator): for file in files: with suppress(FileNotFoundError): file = parent / file if not file.is_sy... |
def TemporaryDirectory(suffix=None, prefix=None, dir=None, on_error='ignore'): # @ReservedAssignment ''' An extension to `tempfile.TemporaryDirectory`. Unlike with `python:tempfile`, a :py:class:`~pathlib.Path` is yielded on ``__enter__``, not a `str`. Parameters ---------- suffix : str See `tempfile.TemporaryDirectory... |
def hash(path, hash_function=hashlib.sha512): # @ReservedAssignment ''' Hash file or directory. Parameters ---------- path : ~pathlib.Path File or directory to hash. hash_function : ~typing.Callable[[], hash object] Function which creates a hashlib hash object when called. Defaults to ``hashlib.sha512``. Returns ------... |
h(dir_name) # h(dir_name2) # , # h(file_name) h(file_content) # h(file_name2) h(file_content2) # ; # h(relative-dir-path2) # ... hash_.update(hash_function(str(Path(directory).relative_to(path)).encode()).digest()) for name in sorted(directories): hash_.update(hash_function(name.encode()).digest()) hash_.update(b',') f... |
def delete_orderrun(self, orderrun_id): """ :param self: self :param orderrun_id: string ; 'good' return a good value ; 'bad' return a bad value :rtype: DKReturnCode """ rc = DKReturnCode() if orderrun_id == 'good': rc.set(rc.DK_SUCCESS, None, None) else: rc.set(rc.DK_FAIL, 'ServingDeleteV2: unable to delete OrderRun')... |
def diff_identifiers(a, b): """Return list of tuples where identifiers in datasets differ. Tuple structure: (identifier, present in a, present in b) :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples where identifiers in datasets differ """ a_ids = set(a.iden... |
def diff_sizes(a, b, progressbar=None): """Return list of tuples where sizes differ. Tuple structure: (identifier, size in a, size in b) Assumes list of identifiers in a and b are identical. :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples for all items wit... |
def diff_content(a, reference, progressbar=None): """Return list of tuples where content differ. Tuple structure: (identifier, hash in a, hash in reference) Assumes list of identifiers in a and b are identical. Storage broker of reference used to generate hash for files in a. :param a: first :class:`dtoolcore.DataSet` ... |
def _insert(self, namespace, stream, events, configuration): """ `stream` is the name of a stream and `events` is a list of (TimeUUID, event) to insert. Make room for the events to insert if necessary by deleting the oldest events. Then insert each event in time sorted order. """ max_items = configuration['max_items'] ... |
def _delete(self, namespace, stream, start_id, end_time, configuration): """ Delete events with id > `start_id` and end_time <= `end_time`. """ start_id_event = Event(start_id) end_id_event = Event(uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST)) stream_events = self.db[namespace][stream] # Find the interval ou... |
def _retrieve(self, namespace, stream, start_id, end_time, order, limit, configuration): """ Yield events from stream starting after the event with id `start_id` until and including events with timestamp `end_time`. """ start_id_event = Event(start_id) end_id_event = Event(uuid_from_kronos_time(end_time, _type=UUIDType... |
def cli(): """Parse options from the command line""" parser = argparse.ArgumentParser(prog="sphinx-serve", formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler="resolve", description=__doc__ ) parser.add_argument("-v", "--version", action="version", version="%(prog)s {0}".format(__version__) ) parse... |
def find_build_dir(path, build="_build"): """try to guess the build folder's location""" path = os.path.abspath(os.path.expanduser(path)) contents = os.listdir(path) filtered_contents = [directory for directory in contents if os.path.isdir(os.path.join(path, directory))] if build in filtered_contents: return os.path.jo... |
def flip_uuid_parts(uuid): """ Flips high and low segments of the timestamp portion of a UUID string. This enables correct lexicographic sorting. Because it is a simple flip, this function works in both directions. """ flipped_uuid = uuid.split('-') flipped_uuid[0], flipped_uuid[2] = flipped_uuid[2], flipped_uuid[0] fl... |
def genExampleStar(binaryLetter='', heirarchy=True): """ generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a system and link everything up """ starPar = StarParameters() starPar.addParam('age', '7.6') starPar.addParam('magB', '9.8') starPar.addParam('magH',... |
def genExamplePlanet(binaryLetter=''): """ Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return: """ planetPar = PlanetParameters() planetPar.addParam('discoverymethod', 'transit') planetPar.addParam('discoveryyear', '2001') planetPar.addParam('e... |
def config_list(backend): """ Print the current configuration """ click.secho('Print Configuration', fg='green') print str(backend.dki.get_config()) |
def recipe_status(backend): """ Compare local recipe to remote recipe for the current recipe. """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You are not in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickExcept... |
def recipe_conflicts(backend): """ See if there are any unresolved conflicts for this recipe. """ recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder.') recipe_name = DKRecipeDisk.find_recipe_name() click.secho("%s - Checking for conflicts o... |
def kitchen_list(backend): """ List all Kitchens """ click.echo(click.style('%s - Getting the list of kitchens' % get_datetime(), fg='green')) check_and_print(DKCloudCommandRunner.list_kitchen(backend.dki)) |
def kitchen_get(backend, kitchen_name, recipe): """ Get an existing Kitchen """ found_kitchen = DKKitchenDisk.find_kitchen_name() if found_kitchen is not None and len(found_kitchen) > 0: raise click.ClickException("You cannot get a kitchen into an existing kitchen directory structure.") if len(recipe) > 0: click.secho(... |
def kitchen_create(backend, parent, kitchen): """ Create a new kitchen """ click.secho('%s - Creating kitchen %s from parent kitchen %s' % (get_datetime(), kitchen, parent), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.create_kitchen(backend.dki, parent, kitch... |
def kitchen_delete(backend, kitchen): """ Provide the name of the kitchen to delete """ click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki, kitchen)) else: raise click.Cli... |
def kitchen_config(backend, kitchen, add, get, unset, listall): """ Get and Set Kitchen variable overrides """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) check_and_print(DKCloudCommandRunner.config_kitchen(backend.dki, use_kitchen, add, get,... |
def kitchen_merge(backend, source_kitchen, target_kitchen): """ Merge two Kitchens """ click.secho('%s - Merging Kitchen %s into Kitchen %s' % (get_datetime(), source_kitchen, target_kitchen), fg='green') check_and_print(DKCloudCommandRunner.merge_kitchens_improved(backend.dki, source_kitchen, target_kitchen)) |
def recipe_list(backend, kitchen): """ List the Recipes in a Kitchen """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho("%s - Getting the list of Recipes for Kitchen '%s'" % (get_datetime(), use_kitchen), fg='green') check_and_print(... |
def recipe_create(backend, kitchen, name): """ Create a new Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho("%s - Creating Recipe %s for Kitchen '%s'" % (get_datetime(), name, use_kitchen), fg='green') check_and_print(DKClo... |
def recipe_get(backend, recipe): """ Get the latest files for this recipe. """ recipe_root_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_root_dir is None: if recipe is None: raise click.ClickException("\nPlease change to a recipe folder or provide a recipe name arguement") # raise click.ClickException('You must b... |
def recipe_compile(backend, kitchen, recipe, variation): """ Apply variables to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException... |
def file_add(backend, kitchen, recipe, message, filepath): """ Add a newly created file to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.Cli... |
def file_update_all(backend, message, dryrun): """ Update all of the changed files for this Recipe """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You must be in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickE... |
def file_resolve(backend, filepath): """ Mark a conflicted file as resolved, so that a merge can be completed """ recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder.') click.secho("%s - Resolving conflicts" % get_datetime()) for file_to_resolve in file... |
def active_serving_watcher(backend, kitchen, period): """ Watches all cooking Recipes in a Kitchen Provide the kitchen name as an argument or be in a Kitchen folder. """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho('%s - Watching A... |
def order_run(backend, kitchen, recipe, variation, node): """ Run an order: cook a recipe variation """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.Cli... |
def order_delete(backend, kitchen, order_id): """ Delete one order or all orders in a kitchen """ use_kitchen = Backend.get_kitchen_name_soft(kitchen) print use_kitchen if use_kitchen is None and order_id is None: raise click.ClickException('You must specify either a kitchen or an order_id or be in a kitchen directory'... |
def order_stop(backend, order_id): """ Stop an order - Turn off the serving generation ability of an order. Stop any running jobs. Keep all state around. """ if order_id is None: raise click.ClickException('invalid order id %s' % order_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_id), fg='green') ch... |
def order_stop(backend, order_run_id): """ Stop the run of an order - Stop the running order and keep all state around. """ if order_run_id is None: raise click.ClickException('invalid order id %s' % order_run_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_run_id), fg='green') check_and_print(DKCloudC... |
def orderrun_detail(backend, kitchen, summary, nodestatus, runstatus, log, timing, test, all_things, order_id, order_run_id, disp_order_id, disp_order_run_id): """ Display information about an Order-Run """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(... |
not specify anything to display, show the summary information if not runstatus and \ not all_things and \ not test and \ not timing and \ not log and \ not nodestatus and \ not summary and \ not disp_order_id and \ not disp_order_run_id: pd['summary'] = True if order_id is not None and order_run_id is not None: raise c... |
def delete_orderrun(backend, orderrun_id): """ Delete the orderrun specified by the argument. """ click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green') check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip())) |
def order_list(backend, kitchen): """ Apply variables to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho('%s - Get Order information for Kitchen %s' % (get_datetime(), use_kitchen), fg='green') check_and_print( DKCloudCom... |
def secret_list(backend,path): """ List all Secrets """ click.echo(click.style('%s - Getting the list of secrets' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_list(backend.dki,path)) |
def secret_write(backend,entry): """ Write a secret """ path,value=entry.split('=') if value.startswith('@'): with open(value[1:]) as vfile: value = vfile.read() click.echo(click.style('%s - Writing secret' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_write(backend.dki,path,value)) |
def puts(text, end="\n", flush=True, stream=sys.stdout): """ Print ``text`` to ``stream`` (default: ``sys.stdout``) and auto-flush. This is useful for fast loops where Python's default IO buffering would prevent "realtime" updating. Newlines may be disabled by setting ``end`` to the empty string (``''``). (This intenti... |
def stream(self): """Returns a stream object (:func:`file`, :class:`~io.BytesIO` or :class:`~StringIO.StringIO`) on the data.""" if not hasattr(self, '_stream'): if self.file is not None: self._stream = self.file elif self.filename is not None: self._stream = open(self.filename, 'rb') elif self.text is not None: self._... |
def readlines(self, *args, **kwargs): """Return list of all lines. Always returns list of unicode.""" return list(iter(partial(self.readline, *args, **kwargs), u'')) |
def save_to(self, file): """Save data to file. Will copy by either writing out the data or using :func:`shutil.copyfileobj`. :param file: A file-like object (with a ``write`` method) or a filename.""" dest = file if hasattr(dest, 'write'): # writing to a file-like # only works when no unicode conversion is done if self... |
def temp_saved(self, suffix='', prefix='tmp', dir=None): """Saves data to temporary file and returns the relevant instance of :func:`~tempfile.NamedTemporaryFile`. The resulting file is not deleted upon closing, but when the context manager exits. Other arguments are passed on to :func:`~tempfile.NamedTemporaryFile`. "... |
def _ions(self, f): """ This is a generator that returns the mzs being measured during each time segment, one segment at a time. """ outside_pos = f.tell() doff = find_offset(f, 4 * b'\xff' + 'HapsSearch'.encode('ascii')) # actual end of prev section is 34 bytes before, but assume 1 rec f.seek(doff - 62) # seek backwar... |
struct.unpack('<' + 8 * 'I', f.read(32)) if itype == 0: # SIM ions.append(i1 / 100.) else: # full scan # TODO: this might be a little hacky? # ideally we would need to know n for this, e.g.: # ions += np.linspace(i1 / 100, i2 / 100, n).tolist() ions += np.arange(i1 / 100., i2 / 100. + 1, 1).tolist() # save the file pos... |
def _emit_message(cls, message): """Print a message to STDOUT.""" sys.stdout.write(message) sys.stdout.flush() |
def _emit_error(cls, message): """Print an error message to STDERR.""" sys.stderr.write('ERROR: {message}\n'.format(message=message)) sys.stderr.flush() |
def _emit_warning(cls, message): """Print an warning message to STDERR.""" sys.stderr.write('WARNING: {message}\n'.format(message=message)) sys.stderr.flush() |
def _setup_piddir(self): """Create the directory for the PID file if necessary.""" if self.pidfile is None: return piddir = os.path.dirname(self.pidfile) if not os.path.isdir(piddir): # Create the directory with sensible mode and ownership os.makedirs(piddir, 0o777 & ~self.umask) os.chown(piddir, self.uid, self.gid) |
def _read_pidfile(self): """Read the PID file and check to make sure it's not stale.""" if self.pidfile is None: return None if not os.path.isfile(self.pidfile): return None # Read the PID file with open(self.pidfile, 'r') as fp: try: pid = int(fp.read()) except ValueError: self._emit_warning('Empty or broken pidfile {... |
def _write_pidfile(self): """Create, write to, and lock the PID file.""" flags = os.O_CREAT | os.O_RDWR try: # Some systems don't have os.O_EXLOCK flags = flags | os.O_EXLOCK except AttributeError: pass self._pid_fd = os.open(self.pidfile, flags, 0o666 & ~self.umask) os.write(self._pid_fd, str(os.getpid()).encode('utf-... |
def _close_pidfile(self): """Closes and removes the PID file.""" if self._pid_fd is not None: os.close(self._pid_fd) try: os.remove(self.pidfile) except OSError as ex: if ex.errno != errno.ENOENT: raise |
def _prevent_core_dump(cls): """Prevent the process from generating a core dump.""" try: # Try to get the current limit resource.getrlimit(resource.RLIMIT_CORE) except ValueError: # System doesn't support the RLIMIT_CORE resource limit return else: # Set the soft and hard limits for core dump size to zero resource.setr... |
def _setup_environment(self): """Setup the environment for the daemon.""" # Save the original working directory so that reload can launch # the new process with the same arguments as the original self._orig_workdir = os.getcwd() if self.chrootdir is not None: try: # Change the root directory os.chdir(self.chrootdir) os... |
to setuid or setgid ' '({error})'.format(error=str(ex))) |
def _reset_file_descriptors(self): """Close open file descriptors and redirect standard streams.""" if self.close_open_files: # Attempt to determine the max number of open files max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if max_fds == resource.RLIM_INFINITY: # If the limit is infinity, use a more reasonabl... |
def _is_socket(cls, stream): """Check if the given stream is a socket.""" try: fd = stream.fileno() except ValueError: # If it has no file descriptor, it's not a socket return False sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW) try: # This will raise a socket.error if it's not a socket sock.getsockopt(socke... |
def _pid_is_alive(cls, pid, timeout): """Check if a PID is alive with a timeout.""" try: proc = psutil.Process(pid) except psutil.NoSuchProcess: return False try: proc.wait(timeout=timeout) except psutil.TimeoutExpired: return True return False |
def _is_detach_necessary(cls): """Check if detaching the process is even necessary.""" if os.getppid() == 1: # Process was started by init return False if cls._is_socket(sys.stdin): # If STDIN is a socket, the daemon was started by a super-server return False return True |
def _detach_process(self): """Detach the process via the standard double-fork method with some extra magic.""" # First fork to return control to the shell pid = os.fork() if pid > 0: # Wait for the first child, because it's going to wait and # check to make sure the second child is actually running # before exiting os.... |
already gone for some reason exitcode = status[1] % 255 self._emit_failed() self._emit_error('Child exited immediately with exit ' 'code {code}'.format(code=exitcode)) sys.exit(exitcode) else: self._emit_ok() sys.exit(0) self._reset_file_descriptors() |
def _orphan_this_process(cls, wait_for_parent=False): """Orphan the current process by forking and then waiting for the parent to exit.""" # The current PID will be the PPID of the forked child ppid = os.getpid() pid = os.fork() if pid > 0: # Exit parent sys.exit(0) if wait_for_parent and cls._pid_is_alive(ppid, timeou... |
def _fork_and_supervise_child(cls): """Fork a child and then watch the process group until there are no processes in it.""" pid = os.fork() if pid == 0: # Fork again but orphan the child this time so we'll have # the original parent and the second child which is orphaned # so we don't have to worry about it becoming a ... |
= psutil.Process(proc.ppid()) while True: try: # Look for other processes in this process group group_procs = [] for proc in psutil.process_iter(): try: if (os.getpgid(proc.pid) == pgid and proc.pid not in exclude_pids): # We found a process in this process group group_procs.append(proc) except (psutil.NoSuchProcess, O... |
def _shutdown(self, message=None, code=0): """Shutdown and cleanup everything.""" if self._shutdown_complete: # Make sure we don't accidentally re-run the all cleanup sys.exit(code) if self.shutdown_callback is not None: # Call the shutdown callback with a message suitable for # logging and the exit code self.shutdown_... |
def _handle_terminate(self, signal_number, _): """Handle a signal to terminate.""" signal_names = { signal.SIGINT: 'SIGINT', signal.SIGQUIT: 'SIGQUIT', signal.SIGTERM: 'SIGTERM', } message = 'Terminated by {name} ({number})'.format( name=signal_names[signal_number], number=signal_number) self._shutdown(message, code=12... |
def _run(self): """Run the worker function with some custom exception handling.""" try: # Run the worker self.worker() except SystemExit as ex: # sys.exit() was called if isinstance(ex.code, int): if ex.code is not None and ex.code != 0: # A custom exit code was specified self._shutdown( 'Exiting with non-zero exit cod... |
def start(self): """Start the daemon.""" if self.worker is None: raise DaemonError('No worker is defined for daemon') if os.environ.get('DAEMONOCLE_RELOAD'): # If this is actually a reload, we need to wait for the # existing daemon to exit first self._emit_message('Reloading {prog} ... '.format(prog=self.prog)) # Orhpa... |
not os.environ.get('DAEMONOCLE_RELOAD'): # This keeps the original parent process open so that we # maintain control of the tty self._fork_and_supervise_child() if not os.environ.get('DAEMONOCLE_RELOAD'): # A custom message is printed for reloading self._emit_message('Starting {prog} ... '.format(prog=self.prog)) self.... |
def stop(self): """Stop the daemon.""" if self.pidfile is None: raise DaemonError('Cannot stop daemon without PID file') pid = self._read_pidfile() if pid is None: # I don't think this should be a fatal error self._emit_warning('{prog} is not running'.format(prog=self.prog)) return self._emit_message('Stopping {prog} .... |
def status(self): """Get the status of the daemon.""" if self.pidfile is None: raise DaemonError('Cannot get status of daemon without PID file') pid = self._read_pidfile() if pid is None: self._emit_message( '{prog} -- not running\n'.format(prog=self.prog)) sys.exit(1) proc = psutil.Process(pid) # Default data data = {... |
data['uptime'] = str(uptime_mins) + 'm' if uptime_hours: uptime_days, uptime_hours = divmod(uptime_hours, 24) data['uptime'] = str(uptime_hours) + 'h ' + data['uptime'] if uptime_days: data['uptime'] = str(uptime_days) + 'd ' + data['uptime'] except psutil.Error: pass template = ('{prog} -- pid: {pid}, status: {status}... |
def list_actions(cls): """Get a list of exposed actions that are callable via the ``do_action()`` method.""" # Make sure these are always at the beginning of the list actions = ['start', 'stop', 'restart', 'status'] # Iterate over the instance attributes checking for actions that # have been exposed for func_name in di... |
def get_action(self, action): """Get a callable action.""" func_name = action.replace('-', '_') if not hasattr(self, func_name): # Function doesn't exist raise DaemonError( 'Invalid action "{action}"'.format(action=action)) func = getattr(self, func_name) if (not hasattr(func, '__call__') or getattr(func, '__daemonocle... |
def reload(self): """Make the daemon reload itself.""" pid = self._read_pidfile() if pid is None or pid != os.getpid(): raise DaemonError( 'Daemon.reload() should only be called by the daemon process ' 'itself') # Copy the current environment new_environ = os.environ.copy() new_environ['DAEMONOCLE_RELOAD'] = 'true' # S... |
def _get_windows(peak_list): """ Given a list of peaks, bin them into windows. """ win_list = [] for t0, t1, hints in peak_list: p_w = (t0, t1) for w in win_list: if p_w[0] <= w[0][1] and p_w[1] >= w[0][0]: w[0] = (min(p_w[0], w[0][0]), max(p_w[1], w[0][1])) w[1].append((t0, t1, hints)) break else: win_list.append([p_w... |
def add_file(self, kitchen, recipe, message, api_file_key, file_contents): """ returns True for success or False for failure '/v2/recipe/create/<string:kitchenname>/<string:recipename>', methods=['PUT'] :param self: DKCloudAPI :param kitchen: basestring :param recipe: basestring -- kitchen name, basestring :param messa... |
False: rc.set(rc.DK_FAIL, 'issue with file_contents parameter') return rc pdict = dict() pdict[self.MESSAGE] = message pdict[self.FILEPATH] = api_file_key pdict[self.FILE] = file_contents url = '%s/v2/recipe/create/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe) try: response = requests.put(url, data=js... |
def get_compiled_serving(self, kitchen, recipe_name, variation_name): """ get the compiled version of arecipe with variables applied for a specific variation in a kitchen returns a dictionary '/v2/servings/compiled/get/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['GET'] :param self: DKClou... |
return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None, rdict[rdict.keys()[0]]) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc |
def merge_kitchens_improved(self, from_kitchen, to_kitchen, resolved_conflicts=None): """ merges kitchens '/v2/kitchen/merge/<string:kitchenname>/<string:kitchenname>', methods=['POST'] :param resolved_conflicts: :param self: DKCloudAPI :param from_kitchen: string :param to_kitchen: string :rtype: dict """ rc = DKRetur... |
def merge_file(self, kitchen, recipe, file_path, file_contents, orig_head, last_file_sha): """ Returns the result of merging a local file with the latest version on the remote. This does not cause any side-effects on the server, and no actual merge is performed in the remote repo. /v2/file/merge/<string:kitchenname>/<s... |
None or isinstance(recipe, basestring) is False or \ file_path is None or isinstance(file_path, basestring) is False or \ orig_head is None or isinstance(orig_head, basestring) is False or \ last_file_sha is None or isinstance(last_file_sha, basestring) is False or \ file_contents is None: rc.set(rc.DK_FAIL, 'One or mo... |
def recipe_status(self, kitchen, recipe, local_dir=None): """ gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :param local_dir: string -- :rtype: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with k... |
= local_dir local_sha = get_directory_sha(check_path) remote_sha = rdict['recipes'][recipe] rv = compare_sha(remote_sha, local_sha) rc.set(rc.DK_SUCCESS, None, rv) else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc |
def recipe_tree(self, kitchen, recipe): """ gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :rtype: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None... |
def create_order(self, kitchen, recipe_name, variation_name, node_name=None): """ Full graph '/v2/order/create/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['PUT'] Single node '/v2/order/create/onenode/<string:kitchenname>/<string:recipename>/<string:variationname>/<string:nodename', method... |
def orderrun_detail(self, kitchen, pdict, return_all_data=False): """ api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST']) :param self: DKCloudAPI :param kitchen: string :param pdict: dict :param return_all_data: boolean :rtype: DKReturnCode """ rc = DKReturnCode() if kitchen is ... |
def list_order(self, kitchen, save_to_file=None): """ List the orders for a kitchen or recipe """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc url = '%s/v2/order/status/%s' % (self.get_url_for_direct_rest_call(), kitchen... |
def _date_trunc(value, timeframe): """ A date flooring function. Returns the closest datetime to the current one that aligns to timeframe. For example, _date_trunc('2014-08-13 05:00:00', DateTrunc.Unit.MONTH) will return a Kronos time representing 2014-08-01 00:00:00. """ if isinstance(value, types.StringTypes): value ... |
def _date_part(value, part): """ Returns a portion of a datetime. Returns the portion of a datetime represented by timeframe. For example, _date_part('2014-08-13 05:00:00', DatePart.Unit.WEEK_DAY) will return 2, for Wednesday. """ if isinstance(value, types.StringTypes): value = parse(value) else: value = kronos_time_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.