sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def select_entry(self, *arguments): """ Select a password from the available choices. :param arguments: Refer to :func:`smart_search()`. :returns: The name of a password (a string) or :data:`None` (when no password matched the given `arguments`). """ ma...
Select a password from the available choices. :param arguments: Refer to :func:`smart_search()`. :returns: The name of a password (a string) or :data:`None` (when no password matched the given `arguments`).
entailment
def simple_search(self, *keywords): """ Perform a simple search for case insensitive substring matches. :param keywords: The string(s) to search for. :returns: The matched password names (a generator of strings). Only passwords whose names matches *all* of the given keywords a...
Perform a simple search for case insensitive substring matches. :param keywords: The string(s) to search for. :returns: The matched password names (a generator of strings). Only passwords whose names matches *all* of the given keywords are returned.
entailment
def smart_search(self, *arguments): """ Perform a smart search on the given keywords or patterns. :param arguments: The keywords or patterns to search for. :returns: The matched password names (a list of strings). :raises: The following exceptions can be raised: ...
Perform a smart search on the given keywords or patterns. :param arguments: The keywords or patterns to search for. :returns: The matched password names (a list of strings). :raises: The following exceptions can be raised: - :exc:`.NoMatchingPasswordError` when no matching pas...
entailment
def entries(self): """A list of :class:`PasswordEntry` objects.""" passwords = [] for store in self.stores: passwords.extend(store.entries) return natsort(passwords, key=lambda e: e.name)
A list of :class:`PasswordEntry` objects.
entailment
def context(self): """ An execution context created using :mod:`executor.contexts`. The value of :attr:`context` defaults to a :class:`~executor.contexts.LocalContext` object with the following characteristics: - The working directory of the execution context is set to ...
An execution context created using :mod:`executor.contexts`. The value of :attr:`context` defaults to a :class:`~executor.contexts.LocalContext` object with the following characteristics: - The working directory of the execution context is set to the value of :attr:`directory...
entailment
def directory(self, value): """Normalize the value of :attr:`directory` when it's set.""" # Normalize the value of `directory'. set_property(self, "directory", parse_path(value)) # Clear the computed values of `context' and `entries'. clear_property(self, "context") clear...
Normalize the value of :attr:`directory` when it's set.
entailment
def entries(self): """A list of :class:`PasswordEntry` objects.""" timer = Timer() passwords = [] logger.info("Scanning %s ..", format_path(self.directory)) listing = self.context.capture("find", "-type", "f", "-name", "*.gpg", "-print0") for filename in split(listing, "\...
A list of :class:`PasswordEntry` objects.
entailment
def ensure_directory_exists(self): """ Make sure :attr:`directory` exists. :raises: :exc:`.MissingPasswordStoreError` when the password storage directory doesn't exist. """ if not os.path.isdir(self.directory): msg = "The password storage directory d...
Make sure :attr:`directory` exists. :raises: :exc:`.MissingPasswordStoreError` when the password storage directory doesn't exist.
entailment
def format_text(self, include_password=True, use_colors=None, padding=True, filters=()): """ Format :attr:`text` for viewing on a terminal. :param include_password: :data:`True` to include the password in the formatted text, :data:`False` to exclude the ...
Format :attr:`text` for viewing on a terminal. :param include_password: :data:`True` to include the password in the formatted text, :data:`False` to exclude the password from the formatted text. :param use_colors: :data:`True` to use ANS...
entailment
def get_diaginfo(diaginfo_file): """ Read an output's diaginfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- diaginfo_file : str Path to diaginfo.dat Returns ------- DataFrame containing the category information. ...
Read an output's diaginfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- diaginfo_file : str Path to diaginfo.dat Returns ------- DataFrame containing the category information.
entailment
def get_tracerinfo(tracerinfo_file): """ Read an output's tracerinfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- tracerinfo_file : str Path to tracerinfo.dat Returns ------- DataFrame containing the tracer informati...
Read an output's tracerinfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- tracerinfo_file : str Path to tracerinfo.dat Returns ------- DataFrame containing the tracer information.
entailment
def read_from_bpch(filename, file_position, shape, dtype, endian, use_mmap=False): """ Read a chunk of data from a bpch output file. Parameters ---------- filename : str Path to file on disk containing the data file_position : int Position (bytes) where desired d...
Read a chunk of data from a bpch output file. Parameters ---------- filename : str Path to file on disk containing the data file_position : int Position (bytes) where desired data chunk begins shape : tuple of ints Resultant (n-dimensional) shape of requested data; the chun...
entailment
def _read(self): """ Helper function to load the data referenced by this bundle. """ if self._dask: d = da.from_delayed( delayed(read_from_bpch, )( self.filename, self.file_position, self.shape, self.dtype, self.endian, use_mmap=self._m...
Helper function to load the data referenced by this bundle.
entailment
def close(self): """ Close this bpch file. """ if not self.fp.closed: for v in list(self.var_data): del self.var_data[v] self.fp.close()
Close this bpch file.
entailment
def _read_metadata(self): """ Read the main metadata packaged within a bpch file, indicating the output filetype and its title. """ filetype = self.fp.readline().strip() filetitle = self.fp.readline().strip() # Decode to UTF string, if possible try: ...
Read the main metadata packaged within a bpch file, indicating the output filetype and its title.
entailment
def _read_header(self): """ Process the header information (data model / grid spec) """ self._header_pos = self.fp.tell() line = self.fp.readline('20sffii') modelname, res0, res1, halfpolar, center180 = line self._attributes.update({ "modelname": str(modelname, 'utf...
Process the header information (data model / grid spec)
entailment
def _read_var_data(self): """ Iterate over the block of this bpch file and return handlers in the form of `BPCHDataBundle`s for access to the data contained therein. """ var_bundles = OrderedDict() var_attrs = OrderedDict() n_vars = 0 while self.fp.tel...
Iterate over the block of this bpch file and return handlers in the form of `BPCHDataBundle`s for access to the data contained therein.
entailment
def broadcast_1d_array(arr, ndim, axis=1): """ Broadcast 1-d array `arr` to `ndim` dimensions on the first axis (`axis`=0) or on the last axis (`axis`=1). Useful for 'outer' calculations involving 1-d arrays that are related to different axes on a multidimensional grid. """ ext_arr = arr ...
Broadcast 1-d array `arr` to `ndim` dimensions on the first axis (`axis`=0) or on the last axis (`axis`=1). Useful for 'outer' calculations involving 1-d arrays that are related to different axes on a multidimensional grid.
entailment
def get_timestamp(time=True, date=True, fmt=None): """ Return the current timestamp in machine local time. Parameters: ----------- time, date : Boolean Flag to include the time or date components, respectively, in the output. fmt : str, optional If passed, will override the ...
Return the current timestamp in machine local time. Parameters: ----------- time, date : Boolean Flag to include the time or date components, respectively, in the output. fmt : str, optional If passed, will override the time/date choice and use as the format string passe...
entailment
def fix_attr_encoding(ds): """ This is a temporary hot-fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the 'scale_factor' and 'units' attributes we encode with the data we ingest, converts the 'hydrocarbon' and 'chemical' attribute to a binary integer ins...
This is a temporary hot-fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the 'scale_factor' and 'units' attributes we encode with the data we ingest, converts the 'hydrocarbon' and 'chemical' attribute to a binary integer instead of a boolean, and removes ...
entailment
def after_output(command_status): """ Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255. """ if command_status not in range(256): raise ValueError("command_status must be an integer in the range 0-255") sys.stdout.write(AFTER_OUTPUT.f...
Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255.
entailment
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for entry_title in orm.NewsEntryTitle.objects.all(): entry = NewsEntry.objects.get(pk=entry_title.entry.pk) entry.translate(e...
Write your forwards methods here.
entailment
def get_cfcompliant_units(units, prefix='', suffix=''): """ Get equivalent units that are compatible with the udunits2 library (thus CF-compliant). Parameters ---------- units : string A string representation of the units. prefix : string Will be added at the beginning of th...
Get equivalent units that are compatible with the udunits2 library (thus CF-compliant). Parameters ---------- units : string A string representation of the units. prefix : string Will be added at the beginning of the returned string (must be a valid udunits2 expression). ...
entailment
def get_valid_varname(varname): """ Replace characters (e.g., ':', '$', '=', '-') of a variable name, which may cause problems when using with (CF-)netCDF based packages. Parameters ---------- varname : string variable name. Notes ----- Characters replacement is based on th...
Replace characters (e.g., ':', '$', '=', '-') of a variable name, which may cause problems when using with (CF-)netCDF based packages. Parameters ---------- varname : string variable name. Notes ----- Characters replacement is based on the table stored in :attr:`VARNAME_MAP_CHA...
entailment
def enforce_cf_variable(var, mask_and_scale=True): """ Given a Variable constructed from GEOS-Chem output, enforce CF-compliant metadata and formatting. Until a bug with lazily-loaded data and masking/scaling is resolved in xarray, you have the option to manually mask and scale the data here. Para...
Given a Variable constructed from GEOS-Chem output, enforce CF-compliant metadata and formatting. Until a bug with lazily-loaded data and masking/scaling is resolved in xarray, you have the option to manually mask and scale the data here. Parameters ---------- var : xarray.Variable A v...
entailment
def published(self, check_language=True, language=None, kwargs=None, exclude_kwargs=None): """ Returns all entries, which publication date has been hit or which have no date and which language matches the current language. """ if check_language: qs ...
Returns all entries, which publication date has been hit or which have no date and which language matches the current language.
entailment
def recent(self, check_language=True, language=None, limit=3, exclude=None, kwargs=None, category=None): """ Returns recently published new entries. """ if category: if not kwargs: kwargs = {} kwargs['categories__in'] = [category] ...
Returns recently published new entries.
entailment
def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry.""" if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 16...
Returns the meta description for the given entry.
entailment
def render_news_placeholder(context, obj, name=False, truncate=False): # pragma: nocover # NOQA """ DEPRECATED: Template tag to render a placeholder from an NewsEntry object We don't need this any more because we don't have a placeholders M2M field on the model any more. Just use the default ``render...
DEPRECATED: Template tag to render a placeholder from an NewsEntry object We don't need this any more because we don't have a placeholders M2M field on the model any more. Just use the default ``render_placeholder`` tag.
entailment
def _requirement_filter_by_marker(req): # type: (pkg_resources.Requirement) -> bool """Check if the requirement is satisfied by the marker. This function checks for a given Requirement whether its environment marker is satisfied on the current platform. Currently only the python version and system ...
Check if the requirement is satisfied by the marker. This function checks for a given Requirement whether its environment marker is satisfied on the current platform. Currently only the python version and system platform are checked.
entailment
def _requirement_find_lowest_possible(req): # type: (pkg_resources.Requirement) -> List[str] """Find lowest required version. Given a single Requirement, this function calculates the lowest required version to satisfy it. If the requirement excludes a specific version, then this version will not be...
Find lowest required version. Given a single Requirement, this function calculates the lowest required version to satisfy it. If the requirement excludes a specific version, then this version will not be used as the minimal supported version. Examples -------- >>> req = pkg_resources.Requirem...
entailment
def _requirements_sanitize(req_list): # type: (List[str]) -> List[str] """ Cleanup a list of requirement strings (e.g. from requirements.txt) to only contain entries valid for this platform and with the lowest required version only. Example ------- >>> from sys import version_info ...
Cleanup a list of requirement strings (e.g. from requirements.txt) to only contain entries valid for this platform and with the lowest required version only. Example ------- >>> from sys import version_info >>> _requirements_sanitize([ ... 'foo>=3.0', ... "monotonic>=1.0,>0.1;p...
entailment
def _ensure_coroutine_function(func): """Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine! """ if asyncio.iscoroutinefunction(func): return func else: @asyncio.coroutine def coroutine_funct...
Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine!
entailment
def location(self): """Return a string uniquely identifying the event. This string can be used to find the event in the event store UI (cf. id attribute, which is the UUID that at time of writing doesn't let you easily find the event). """ if self._location is None: ...
Return a string uniquely identifying the event. This string can be used to find the event in the event store UI (cf. id attribute, which is the UUID that at time of writing doesn't let you easily find the event).
entailment
async def find_backwards(self, stream_name, predicate, predicate_label='predicate'): """Return first event matching predicate, or None if none exists. Note: 'backwards', both here and in Event Store, means 'towards the event emitted furthest in the past'. """ logger = self._logg...
Return first event matching predicate, or None if none exists. Note: 'backwards', both here and in Event Store, means 'towards the event emitted furthest in the past'.
entailment
def main(): """Command line interface for the ``qpass`` program.""" # Initialize logging to the terminal. coloredlogs.install() # Prepare for command line argument parsing. action = show_matching_entry program_opts = dict(exclude_list=[]) show_opts = dict(filters=[], use_clipboard=is_clipboa...
Command line interface for the ``qpass`` program.
entailment
def edit_matching_entry(program, arguments): """Edit the matching entry.""" entry = program.select_entry(*arguments) entry.context.execute("pass", "edit", entry.name)
Edit the matching entry.
entailment
def list_matching_entries(program, arguments): """List the entries matching the given keywords/patterns.""" output("\n".join(entry.name for entry in program.smart_search(*arguments)))
List the entries matching the given keywords/patterns.
entailment
def show_matching_entry(program, arguments, use_clipboard=True, quiet=False, filters=()): """Show the matching entry on the terminal (and copy the password to the clipboard).""" entry = program.select_entry(*arguments) if not quiet: formatted_entry = entry.format_text(include_password=not use_clipbo...
Show the matching entry on the terminal (and copy the password to the clipboard).
entailment
def parse_parameters(payflowpro_response_data): """ Parses a set of Payflow Pro response parameter name and value pairs into a list of PayflowProObjects, and returns a tuple containing the object list and a dictionary containing any unconsumed data. The first item in the object list will alwa...
Parses a set of Payflow Pro response parameter name and value pairs into a list of PayflowProObjects, and returns a tuple containing the object list and a dictionary containing any unconsumed data. The first item in the object list will always be the Response object, and the RecurringPayments obj...
entailment
def convert(document, canvas, items=None, tounicode=None): """ Convert 'items' stored in 'canvas' to SVG 'document'. If 'items' is None, then all items are convered. tounicode is a function that get text and returns it's unicode representation. It should be used when national characters are used on canvas. Ret...
Convert 'items' stored in 'canvas' to SVG 'document'. If 'items' is None, then all items are convered. tounicode is a function that get text and returns it's unicode representation. It should be used when national characters are used on canvas. Return list of XML elements
entailment
def SVGdocument(): "Create default SVG document" import xml.dom.minidom implementation = xml.dom.minidom.getDOMImplementation() doctype = implementation.createDocumentType( "svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" ) document= implementation.createDocument(None, "sv...
Create default SVG document
entailment
def segment_to_line(document, coords): "polyline with 2 vertices using <line> tag" return setattribs( document.createElement('line'), x1 = coords[0], y1 = coords[1], x2 = coords[2], y2 = coords[3], )
polyline with 2 vertices using <line> tag
entailment
def polyline(document, coords): "polyline with more then 2 vertices" points = [] for i in range(0, len(coords), 2): points.append("%s,%s" % (coords[i], coords[i+1])) return setattribs( document.createElement('polyline'), points = ' '.join(points), )
polyline with more then 2 vertices
entailment
def smoothline(document, coords): "smoothed polyline" element = document.createElement('path') path = [] points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] def pt(points): x0, y0 = points[0] x1, y1 = points[1] p0 = (2*x0-x1, 2*y0-y1) x0, y0 = points[-1] x1, y1 = points[-2] ...
smoothed polyline
entailment
def cubic_bezier(document, coords): "cubic bezier polyline" element = document.createElement('path') points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] path = ["M%s %s" %points[0]] for n in xrange(1, len(points), 3): A, B, C = points[n:n+3] path.append("C%s,%s %s,%s %s,%s" % (A[0], A[1]...
cubic bezier polyline
entailment
def smoothpolygon(document, coords): "smoothed filled polygon" element = document.createElement('path') path = [] points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] def pt(points): p = points n = len(points) for i in range(0, len(points)): a = p[(i-1) % n] b = p[i] c = p[(i...
smoothed filled polygon
entailment
def oval(document, coords): "circle/ellipse" x1, y1, x2, y2 = coords # circle if x2-x1 == y2-y1: return setattribs(document.createElement('circle'), cx = (x1+x2)/2, cy = (y1+y2)/2, r = abs(x2-x1)/2, ) # ellipse else: return setattribs(document.createElement('ellipse'), cx = (x1+x2)/2, cy ...
circle/ellipse
entailment
def arc(document, bounding_rect, start, extent, style): "arc, pieslice (filled), arc with chord (filled)" (x1, y1, x2, y2) = bounding_rect import math cx = (x1 + x2)/2.0 cy = (y1 + y2)/2.0 rx = (x2 - x1)/2.0 ry = (y2 - y1)/2.0 start = math.radians(float(start)) extent = math.radians(float(extent)) # fr...
arc, pieslice (filled), arc with chord (filled)
entailment
def HTMLcolor(canvas, color): "returns Tk color in form '#rrggbb' or '#rgb'" if color: # r, g, b \in [0..2**16] r, g, b = ["%02x" % (c // 256) for c in canvas.winfo_rgb(color)] if (r[0] == r[1]) and (g[0] == g[1]) and (b[0] == b[1]): # shorter form #rgb return "#" + r[0] + g[0] + b[0] else: return ...
returns Tk color in form '#rrggbb' or '#rgb
entailment
def arrow_head(document, x0, y0, x1, y1, arrowshape): "make arrow head at (x1,y1), arrowshape is tuple (d1, d2, d3)" import math dx = x1 - x0 dy = y1 - y0 poly = document.createElement('polygon') d = math.sqrt(dx*dx + dy*dy) if d == 0.0: # XXX: equal, no "close enough" return poly try: d1, d2, d3 = l...
make arrow head at (x1,y1), arrowshape is tuple (d1, d2, d3)
entailment
def font_actual(tkapp, font): "actual font parameters" tmp = tkapp.call('font', 'actual', font) return dict( (tmp[i][1:], tmp[i+1]) for i in range(0, len(tmp), 2) )
actual font parameters
entailment
def parse_dash(string, width): "parse dash pattern specified with string" # DashConvert from {tk-sources}/generic/tkCanvUtil.c w = max(1, int(width + 0.5)) n = len(string) result = [] for i, c in enumerate(string): if c == " " and len(result): result[-1] += w + 1 elif c == "_": result.append(8*w) ...
parse dash pattern specified with string
entailment
def prof_altitude(pressure, p_coef=(-0.028389, -0.0493698, 0.485718, 0.278656, -17.5703, 48.0926)): """ Return altitude for given pressure. This function evaluates a polynomial at log10(pressure) values. Parameters ---------- pressure : array-like pr...
Return altitude for given pressure. This function evaluates a polynomial at log10(pressure) values. Parameters ---------- pressure : array-like pressure values [hPa]. p_coef : array-like coefficients of the polynomial (default values are for the US Standard Atmosphere). ...
entailment
def prof_pressure(altitude, z_coef=(1.94170e-9, -5.14580e-7, 4.57018e-5, -1.55620e-3, -4.61994e-2, 2.99955)): """ Return pressure for given altitude. This function evaluates a polynomial at altitudes values. Parameters ---------- altitude : array-like ...
Return pressure for given altitude. This function evaluates a polynomial at altitudes values. Parameters ---------- altitude : array-like altitude values [km]. z_coef : array-like coefficients of the polynomial (default values are for the US Standard Atmosphere). Retur...
entailment
def _find_references(model_name, references=None): """ Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child). """ references = references or [] references.append(model_name) ref = M...
Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child).
entailment
def _get_model_info(model_name): """ Get the grid specifications for a given model. Parameters ---------- model_name : string Name of the model. Supports multiple formats (e.g., 'GEOS5', 'GEOS-5' or 'GEOS_5'). Returns ------- specifications : dict Grid specifica...
Get the grid specifications for a given model. Parameters ---------- model_name : string Name of the model. Supports multiple formats (e.g., 'GEOS5', 'GEOS-5' or 'GEOS_5'). Returns ------- specifications : dict Grid specifications as a dictionary. Raises ------...
entailment
def _get_archive_filelist(filename): # type: (str) -> List[str] """Extract the list of files from a tar or zip archive. Args: filename: name of the archive Returns: Sorted list of files in the archive, excluding './' Raises: ValueError: when the file is neither a zip nor a...
Extract the list of files from a tar or zip archive. Args: filename: name of the archive Returns: Sorted list of files in the archive, excluding './' Raises: ValueError: when the file is neither a zip nor a tar archive FileNotFoundError: when the provided file does not exi...
entailment
def _augment_book(self, uuid, event): """ Checks if the newly created object is a book and only has an ISBN. If so, tries to fetch the book data off the internet. :param uuid: uuid of book to augment :param client: requesting client """ try: if not is...
Checks if the newly created object is a book and only has an ISBN. If so, tries to fetch the book data off the internet. :param uuid: uuid of book to augment :param client: requesting client
entailment
def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system Courtesy: Thomas ( http://stackoverflow.com/questions/12090503 /listing-available-com-p...
Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system Courtesy: Thomas ( http://stackoverflow.com/questions/12090503 /listing-available-com-ports-with-python )
entailment
def opened(self, *args): """Initiates communication with the remote controlled device. :param args: """ self._serial_open = True self.log("Opened: ", args, lvl=debug) self._send_command(b'l,1') # Saying hello, shortly self.log("Turning off engine, pump and neut...
Initiates communication with the remote controlled device. :param args:
entailment
def on_machinerequest(self, event): """ Sets a new machine speed. :param event: """ self.log("Updating new machine power: ", event.controlvalue) self._handle_servo(self._machine_channel, event.controlvalue)
Sets a new machine speed. :param event:
entailment
def on_rudderrequest(self, event): """ Sets a new rudder angle. :param event: """ self.log("Updating new rudder angle: ", event.controlvalue) self._handle_servo(self._rudder_channel, event.controlvalue)
Sets a new rudder angle. :param event:
entailment
def on_pumprequest(self, event): """ Activates or deactivates a connected pump. :param event: """ self.log("Updating pump status: ", event.controlvalue) self._set_digital_pin(self._pump_channel, event.controlvalue)
Activates or deactivates a connected pump. :param event:
entailment
def provisionList(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provisions a list of items according to their schema :param items: A list of provisionable items. :param database_object: A warmongo database object :param overwrite: Causes existing items to be overwritten...
Provisions a list of items according to their schema :param items: A list of provisionable items. :param database_object: A warmongo database object :param overwrite: Causes existing items to be overwritten :param clear: Clears the collection first (Danger!) :param skip_user_check: Skips checking i...
entailment
def DefaultExtension(schema_obj, form_obj, schemata=None): """Create a default field""" if schemata is None: schemata = ['systemconfig', 'profile', 'client'] DefaultExtends = { 'schema': { "properties/modules": [ schema_obj ] }, 'form...
Create a default field
entailment
def copytree(root_src_dir, root_dst_dir, hardlink=True): """Copies a whole directory tree""" for src_dir, dirs, files in os.walk(root_src_dir): dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1) if not os.path.exists(dst_dir): os.makedirs(dst_dir) for file_ in files: ...
Copies a whole directory tree
entailment
def install_frontend(instance='default', forcereload=False, forcerebuild=False, forcecopy=True, install=True, development=False, build_type='dist'): """Builds and installs the frontend""" hfoslog("Updating frontend components", emitter='BUILDER') components = {} loadable_components...
Builds and installs the frontend
entailment
def config(ctx): """[GROUP] Configuration management operations""" from hfos import database database.initialize(ctx.obj['dbhost'], ctx.obj['dbname']) from hfos.schemata.component import ComponentConfigSchemaTemplate ctx.obj['col'] = model_factory(ComponentConfigSchemaTemplate)
[GROUP] Configuration management operations
entailment
def delete(ctx, componentname): """Delete an existing component configuration. This will trigger the creation of its default configuration upon next restart.""" col = ctx.obj['col'] if col.count({'name': componentname}) > 1: log('More than one component configuration of this name! Try ' ...
Delete an existing component configuration. This will trigger the creation of its default configuration upon next restart.
entailment
def show(ctx, component): """Show the stored, active configuration of a component.""" col = ctx.obj['col'] if col.count({'name': component}) > 1: log('More than one component configuration of this name! Try ' 'one of the uuids as argument. Get a list with "config ' 'list"')...
Show the stored, active configuration of a component.
entailment
def separate_string(string): """ >>> separate_string("test <2>") (['test ', ''], ['2']) """ string_list = regex.split(r'<(?![!=])', regex.sub(r'>', '<', string)) return string_list[::2], string_list[1::2]
>>> separate_string("test <2>") (['test ', ''], ['2'])
entailment
def overlapping(start1, end1, start2, end2): """ >>> overlapping(0, 5, 6, 7) False >>> overlapping(1, 2, 0, 4) True >>> overlapping(5,6,0,5) False """ return not ((start1 <= start2 and start1 <= end2 and end1 <= end2 and end1 <= start2) or (start1 >= start2 and start1...
>>> overlapping(0, 5, 6, 7) False >>> overlapping(1, 2, 0, 4) True >>> overlapping(5,6,0,5) False
entailment
def remove_lower_overlapping(current, higher): """ >>> remove_lower_overlapping([], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 0, 4)], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 5, 6)], [('a', 0, 5)]) [('z', 5, 6), ('a', 0, 5)] """ for (mat...
>>> remove_lower_overlapping([], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 0, 4)], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 5, 6)], [('a', 0, 5)]) [('z', 5, 6), ('a', 0, 5)]
entailment
def debugrequest(self, event): """Handler for client-side debug requests""" try: self.log("Event: ", event.__dict__, lvl=critical) if event.data == "storejson": self.log("Storing received object to /tmp", lvl=critical) fp = open('/tmp/hfosdebugger...
Handler for client-side debug requests
entailment
def stdin_read(self, data): """read Event (on channel ``stdin``) This is the event handler for ``read`` events specifically from the ``stdin`` channel. This is triggered each time stdin has data that it has read. """ data = data.strip().decode("utf-8") self.log("...
read Event (on channel ``stdin``) This is the event handler for ``read`` events specifically from the ``stdin`` channel. This is triggered each time stdin has data that it has read.
entailment
def register_event(self, event): """Registers a new command line interface event hook as command""" self.log('Registering event hook:', event.cmd, event.thing, pretty=True, lvl=verbose) self.hooks[event.cmd] = event.thing
Registers a new command line interface event hook as command
entailment
def populate_user_events(): """Generate a list of all registered authorized and anonymous events""" global AuthorizedEvents global AnonymousEvents def inheritors(klass): """Find inheritors of a specified object class""" subclasses = {} subclasses_set = set() work = [kl...
Generate a list of all registered authorized and anonymous events
entailment
def db(ctx): """[GROUP] Database management operations""" from hfos import database database.initialize(ctx.obj['dbhost'], ctx.obj['dbname']) ctx.obj['db'] = database
[GROUP] Database management operations
entailment
def clear(ctx, schema): """Clears an entire database collection irrevocably. Use with caution!""" response = _ask('Are you sure you want to delete the collection "%s"' % ( schema), default='N', data_type='bool') if response is True: host, port = ctx.obj['dbhost'].split(':') client ...
Clears an entire database collection irrevocably. Use with caution!
entailment
def provision_system_config(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provision a basic system configuration""" from hfos.provisions.base import provisionList from hfos.database import objectmodels default_system_config_count = objectmodels['systemconfig'].count({ ...
Provision a basic system configuration
entailment
def ICALImporter(ctx, filename, all, owner, calendar, create_calendar, clear_calendar, dry, execfilter): """Calendar Importer for iCal (ics) files """ log('iCal importer running') objectmodels = ctx.obj['db'].objectmodels if objectmodels['user'].count({'name': owner}) > 0: owner_object =...
Calendar Importer for iCal (ics) files
entailment
def make_migrations(schema=None): """Create migration data for a specified schema""" entrypoints = {} old = {} def apply_migrations(migrations, new_model): """Apply migration data to compile an up to date model""" def get_path(raw_path): """Get local path of schema definit...
Create migration data for a specified schema
entailment
def userlogin(self, event): """Provides the newly authenticated user with a backlog and general channel status information""" try: user_uuid = event.useruuid user = objectmodels['user'].find_one({'uuid': user_uuid}) if user_uuid not in self.lastlogs: ...
Provides the newly authenticated user with a backlog and general channel status information
entailment
def join(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: channel_uuid = event.data user_uuid = event.user.uuid if channel_uuid in self.chat_channels: self.log('User j...
Chat event handler for incoming events :param event: say-event with incoming chat message
entailment
def say(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: userid = event.user.uuid recipient = self._get_recipient(event) content = self._get_content(event) message = objec...
Chat event handler for incoming events :param event: say-event with incoming chat message
entailment
def install_docs(instance, clear_target): """Builds and installs the complete HFOS documentation.""" _check_root() def make_docs(): """Trigger a Sphinx make command to build the documentation.""" log("Generating HTML documentation") try: build = Popen( ...
Builds and installs the complete HFOS documentation.
entailment
def var(ctx, clear_target, clear_all): """Install variable data to /var/[lib,cache]/hfos""" install_var(str(ctx.obj['instance']), clear_target, clear_all)
Install variable data to /var/[lib,cache]/hfos
entailment
def install_var(instance, clear_target, clear_all): """Install required folders in /var""" _check_root() log("Checking frontend library and cache directories", emitter='MANAGE') uid = pwd.getpwnam("hfos").pw_uid gid = grp.getgrnam("hfos").gr_gid join = os.path.join # If these nee...
Install required folders in /var
entailment
def provisions(ctx, provision, clear_existing, overwrite, list_provisions): """Install default provisioning data""" install_provisions(ctx, provision, clear_existing, overwrite, list_provisions)
Install default provisioning data
entailment
def install_provisions(ctx, provision, clear_provisions=False, overwrite=False, list_provisions=False): """Install default provisioning data""" log("Installing HFOS default provisions") # from hfos.logger import verbosity, events # verbosity['console'] = verbosity['global'] = events from hfos imp...
Install default provisioning data
entailment
def install_modules(wip): """Install the plugin modules""" def install_module(hfos_module): """Install a single module via setuptools""" try: setup = Popen( [ sys.executable, 'setup.py', 'develop' ...
Install the plugin modules
entailment
def service(ctx): """Install systemd service configuration""" install_service(ctx.obj['instance'], ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port'])
Install systemd service configuration
entailment
def install_service(instance, dbhost, dbname, port): """Install systemd service configuration""" _check_root() log("Installing systemd service") launcher = os.path.realpath(__file__).replace('manage', 'launcher') executable = sys.executable + " " + launcher executable += " --instance " + inst...
Install systemd service configuration
entailment
def nginx(ctx, hostname): """Install nginx configuration""" install_nginx(ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port'], hostname)
Install nginx configuration
entailment
def install_nginx(instance, dbhost, dbname, port, hostname=None): """Install nginx configuration""" _check_root() log("Installing nginx configuration") if hostname is None: try: configuration = _get_system_configuration(dbhost, dbname) hostname = configuration.hostname...
Install nginx configuration
entailment
def install_cert(selfsigned): """Install a local SSL certificate""" _check_root() if selfsigned: log('Generating self signed (insecure) certificate/key ' 'combination') try: os.mkdir('/etc/ssl/certs/hfos') except FileExistsError: pass ex...
Install a local SSL certificate
entailment
def frontend(ctx, dev, rebuild, no_install, build_type): """Build and install frontend""" install_frontend(instance=ctx.obj['instance'], forcerebuild=rebuild, development=dev, install=not no_install, build_type=build_type)
Build and install frontend
entailment
def install_all(ctx, clear_all): """Default-Install everything installable \b This includes * System user (hfos.hfos) * Self signed certificate * Variable data locations (/var/lib/hfos and /var/cache/hfos) * All the official modules in this repository * Default module provisioning data ...
Default-Install everything installable \b This includes * System user (hfos.hfos) * Self signed certificate * Variable data locations (/var/lib/hfos and /var/cache/hfos) * All the official modules in this repository * Default module provisioning data * Documentation * systemd servic...
entailment
def uninstall(): """Uninstall data and resource locations""" _check_root() response = _ask("This will delete all data of your HFOS installations! Type" "YES to continue:", default="N", show_hint=False) if response == 'YES': shutil.rmtree('/var/lib/hfos') shutil.rmtr...
Uninstall data and resource locations
entailment