sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def update(ctx, no_restart, no_rebuild):
"""Update a HFOS node"""
# 0. (NOT YET! MAKE A BACKUP OF EVERYTHING)
# 1. update repository
# 2. update frontend repository
# 3. (Not yet: update venv)
# 4. rebuild frontend
# 5. restart service
instance = ctx.obj['instance']
log('Pulling g... | Update a HFOS node | entailment |
def raw_data(self, event):
"""Handles incoming raw sensor data
:param event: Raw sentences incoming data
"""
self.log('Received raw data from bus', lvl=events)
if not parse:
return
nmea_time = event.data[0]
try:
parsed_data = parse(event.... | Handles incoming raw sensor data
:param event: Raw sentences incoming data | entailment |
def clear_all():
"""DANGER!
*This command is a maintenance tool and clears the complete database.*
"""
sure = input("Are you sure to drop the complete database content? (Type "
"in upppercase YES)")
if not (sure == 'YES'):
db_log('Not deleting the database.')
sys.ex... | DANGER!
*This command is a maintenance tool and clears the complete database.* | entailment |
def _build_model_factories(store):
"""Generate factories to construct objects from schemata"""
result = {}
for schemaname in store:
schema = None
try:
schema = store[schemaname]['schema']
except KeyError:
schemata_log("No schema found for ", schemaname, lv... | Generate factories to construct objects from schemata | entailment |
def _build_collections(store):
"""Generate database collections with indices from the schemastore"""
result = {}
client = pymongo.MongoClient(host=dbhost, port=dbport)
db = client[dbname]
for schemaname in store:
schema = None
indices = None
try:
schema = sto... | Generate database collections with indices from the schemastore | entailment |
def initialize(address='127.0.0.1:27017', database_name='hfos', instance_name="default", reload=False):
"""Initializes the database connectivity, schemata and finally object models"""
global schemastore
global l10n_schemastore
global objectmodels
global collections
global dbhost
global dbpo... | Initializes the database connectivity, schemata and finally object models | entailment |
def profile(schemaname='sensordata', profiletype='pjs'):
"""Profiles object model handling with a very simple benchmarking test"""
db_log("Profiling ", schemaname)
schema = schemastore[schemaname]['schema']
db_log("Schema: ", schema, lvl=debug)
testclass = None
if profiletype == 'warmongo':... | Profiles object model handling with a very simple benchmarking test | entailment |
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit):
"""Exports all collections to (JSON-) files."""
export_format = export_format.upper()
if pretty:
indent = 4
else:
indent = 0
f = None
if filename:
try:
f = open(fil... | Exports all collections to (JSON-) files. | entailment |
def _check_collections(self):
"""Checks node local collection storage sizes"""
self.collection_sizes = {}
self.collection_total = 0
for col in self.db.collection_names(include_system_collections=False):
self.collection_sizes[col] = self.db.command('collstats', col).get(
... | Checks node local collection storage sizes | entailment |
def _check_free_space(self):
"""Checks used filesystem storage sizes"""
def get_folder_size(path):
"""Aggregates used size of a specified path, recursively"""
total_size = 0
for item in walk(path):
for file in item[2]:
try:
... | Checks used filesystem storage sizes | entailment |
def send_mail_worker(config, mail, event):
"""Worker task to send out an email, which blocks the process unless it is threaded"""
log = ""
try:
if config.mail_ssl:
server = SMTP_SSL(config.mail_server, port=config.mail_server_port, timeout=30)
else:
server = SMTP(con... | Worker task to send out an email, which blocks the process unless it is threaded | entailment |
def reload_configuration(self, event):
"""Reload the current configuration and set up everything depending on it"""
super(EnrolManager, self).reload_configuration(event)
self.log('Reloaded configuration.')
self._setup() | Reload the current configuration and set up everything depending on it | entailment |
def change(self, event):
"""An admin user requests a change to an enrolment"""
uuid = event.data['uuid']
status = event.data['status']
if status not in ['Open', 'Pending', 'Accepted', 'Denied', 'Resend']:
self.log('Erroneous status for enrollment requested!', lvl=warn)
... | An admin user requests a change to an enrolment | entailment |
def changepassword(self, event):
"""An enrolled user wants to change their password"""
old = event.data['old']
new = event.data['new']
uuid = event.user.uuid
# TODO: Write email to notify user of password change
user = objectmodels['user'].find_one({'uuid': uuid})
... | An enrolled user wants to change their password | entailment |
def invite(self, event):
"""A new user has been invited to enrol by an admin user"""
self.log('Inviting new user to enrol')
name = event.data['name']
email = event.data['email']
method = event.data['method']
self._invite(name, method, email, event.client.uuid, event) | A new user has been invited to enrol by an admin user | entailment |
def enrol(self, event):
"""A user tries to self-enrol with the enrolment form"""
if self.config.allow_registration is False:
self.log('Someone tried to register although enrolment is closed.')
return
self.log('Client trying to register a new account:', event, pretty=Tru... | A user tries to self-enrol with the enrolment form | entailment |
def accept(self, event):
"""A challenge/response for an enrolment has been accepted"""
self.log('Invitation accepted:', event.__dict__, lvl=debug)
try:
uuid = event.data
enrollment = objectmodels['enrollment'].find_one({
'uuid': uuid
})
... | A challenge/response for an enrolment has been accepted | entailment |
def status(self, event):
"""An anonymous client wants to know if we're open for enrollment"""
self.log('Registration status requested')
response = {
'component': 'hfos.enrol.enrolmanager',
'action': 'status',
'data': self.config.allow_registration
}
... | An anonymous client wants to know if we're open for enrollment | entailment |
def request_reset(self, event):
"""An anonymous client requests a password reset"""
self.log('Password reset request received:', event.__dict__, lvl=hilight)
user_object = objectmodels['user']
email = event.data.get('email', None)
email_user = None
if email is not Non... | An anonymous client requests a password reset | entailment |
def captcha_transmit(self, captcha, uuid):
"""Delayed transmission of a requested captcha"""
self.log('Transmitting captcha')
response = {
'component': 'hfos.enrol.enrolmanager',
'action': 'captcha',
'data': b64encode(captcha['image'].getvalue()).decode('utf... | Delayed transmission of a requested captcha | entailment |
def _invite(self, name, method, email, uuid, event, password=""):
"""Actually invite a given user"""
props = {
'uuid': std_uuid(),
'status': 'Open',
'name': name,
'method': method,
'email': email,
'password': password,
... | Actually invite a given user | entailment |
def _create_user(self, username, password, mail, method, uuid):
"""Create a new user and all initial data"""
try:
if method == 'Invited':
config_role = self.config.group_accept_invited
else:
config_role = self.config.group_accept_enrolled
... | Create a new user and all initial data | entailment |
def _send_invitation(self, enrollment, event):
"""Send an invitation mail to an open enrolment"""
self.log('Sending enrollment status mail to user')
self._send_mail(self.config.invitation_subject, self.config.invitation_mail, enrollment, event) | Send an invitation mail to an open enrolment | entailment |
def _send_acceptance(self, enrollment, password, event):
"""Send an acceptance mail to an open enrolment"""
self.log('Sending acceptance status mail to user')
if password is not "":
password_hint = '\n\nPS: Your new password is ' + password + ' - please change it after your first l... | Send an acceptance mail to an open enrolment | entailment |
def _send_mail(self, subject, template, enrollment, event):
"""Connect to mail server and send actual email"""
context = {
'name': enrollment.name,
'invitation_url': self.invitation_url,
'node_name': self.node_name,
'node_url': self.node_url,
... | Connect to mail server and send actual email | 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)
if self.config.... | Chat event handler for incoming events
:param event: say-event with incoming chat message | entailment |
def add_auth_hook(self, event):
"""Register event hook on reception of add_auth_hook-event"""
self.log('Adding authentication hook for', event.authenticator_name)
self.auth_hooks[event.authenticator_name] = event.event | Register event hook on reception of add_auth_hook-event | entailment |
def _fail(self, event, message='Invalid credentials'):
"""Sends a failure message to the requesting client"""
notification = {
'component': 'auth',
'action': 'fail',
'data': message
}
ip = event.sock.getpeername()[0]
self.failing_clients[ip]... | Sends a failure message to the requesting client | entailment |
def _login(self, event, user_account, user_profile, client_config):
"""Send login notification to client"""
user_account.lastlogin = std_now()
user_account.save()
user_account.passhash = ""
self.fireEvent(
authentication(user_account.name, (
user_acc... | Send login notification to client | entailment |
def authenticationrequest(self, event):
"""Handles authentication requests from clients
:param event: AuthenticationRequest with user's credentials
"""
if event.sock.getpeername()[0] in self.failing_clients:
self.log('Client failed a login and has to wait', lvl=debug)
... | Handles authentication requests from clients
:param event: AuthenticationRequest with user's credentials | entailment |
def _handle_autologin(self, event):
"""Automatic logins for client configurations that allow it"""
self.log("Verifying automatic login request")
# TODO: Check for a common secret
# noinspection PyBroadException
try:
client_config = objectmodels['client'].find_one({... | Automatic logins for client configurations that allow it | entailment |
def _handle_login(self, event):
"""Manual password based login"""
# TODO: Refactor to simplify
self.log("Auth request for ", event.username, 'client:',
event.clientuuid)
# TODO: Define the requirements for secure passwords etc.
# They're also required in the E... | Manual password based login | entailment |
def _get_profile(self, user_account):
"""Retrieves a user's profile"""
try:
# TODO: Load active profile, not just any
user_profile = objectmodels['profile'].find_one(
{'owner': str(user_account.uuid)})
self.log("Profile: ", user_profile,
... | Retrieves a user's profile | entailment |
def _parse(self, bus, data):
"""
Called when a sensor sends a new raw data to this serial connector.
The data is sanitized and sent to the registered protocol
listeners as time/raw/bus sentence tuple.
"""
sen_time = time.time()
try:
# Split up multi... | Called when a sensor sends a new raw data to this serial connector.
The data is sanitized and sent to the registered protocol
listeners as time/raw/bus sentence tuple. | entailment |
def serial_packet(self, event):
"""Handles incoming raw sensor data
:param data: raw incoming data
"""
self.log('Incoming serial packet:', event.__dict__, lvl=verbose)
if self.scanning:
pass
else:
# self.log("Incoming data: ", '%.50s ...' % event... | Handles incoming raw sensor data
:param data: raw incoming data | entailment |
def main():
"""Entry point for the script"""
desc = 'Converts between geodetic, modified apex, quasi-dipole and MLT'
parser = argparse.ArgumentParser(description=desc, prog='apexpy')
parser.add_argument('source', metavar='SOURCE',
choices=['geo', 'apex', 'qd', 'mlt'],
... | Entry point for the script | entailment |
def run_process(cwd, args):
"""Executes an external process via subprocess.Popen"""
try:
process = check_output(args, cwd=cwd, stderr=STDOUT)
return process
except CalledProcessError as e:
log('Uh oh, the teapot broke again! Error:', e, type(e), lvl=verbose, pretty=True)
log... | Executes an external process via subprocess.Popen | entailment |
def _ask_password():
"""Securely and interactively ask for a password"""
password = "Foo"
password_trial = ""
while password != password_trial:
password = getpass.getpass()
password_trial = getpass.getpass(prompt="Repeat:")
if password != password_trial:
print("\nPa... | Securely and interactively ask for a password | entailment |
def _get_credentials(username=None, password=None, dbhost=None):
"""Obtain user credentials by arguments or asking the user"""
# Database salt
system_config = dbhost.objectmodels['systemconfig'].find_one({
'active': True
})
try:
salt = system_config.salt.encode('ascii')
except ... | Obtain user credentials by arguments or asking the user | entailment |
def _ask(question, default=None, data_type='str', show_hint=False):
"""Interactively ask the user for data"""
data = default
if data_type == 'bool':
data = None
default_string = "Y" if default else "N"
while data not in ('Y', 'J', 'N', '1', '0'):
data = input("%s? [%s]... | Interactively ask the user for data | entailment |
def checklat(lat, name='lat'):
"""Makes sure the latitude is inside [-90, 90], clipping close values
(tolerance 1e-4).
Parameters
==========
lat : array_like
latitude
name : str, optional
parameter name to use in the exception message
Returns
=======
lat : ndarray o... | Makes sure the latitude is inside [-90, 90], clipping close values
(tolerance 1e-4).
Parameters
==========
lat : array_like
latitude
name : str, optional
parameter name to use in the exception message
Returns
=======
lat : ndarray or float
Same as input where va... | entailment |
def getsinIm(alat):
"""Computes sinIm from modified apex latitude.
Parameters
==========
alat : array_like
Modified apex latitude
Returns
=======
sinIm : ndarray or float
"""
alat = np.float64(alat)
return 2*np.sin(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(al... | Computes sinIm from modified apex latitude.
Parameters
==========
alat : array_like
Modified apex latitude
Returns
=======
sinIm : ndarray or float | entailment |
def getcosIm(alat):
"""Computes cosIm from modified apex latitude.
Parameters
==========
alat : array_like
Modified apex latitude
Returns
=======
cosIm : ndarray or float
"""
alat = np.float64(alat)
return np.cos(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(alat... | Computes cosIm from modified apex latitude.
Parameters
==========
alat : array_like
Modified apex latitude
Returns
=======
cosIm : ndarray or float | entailment |
def toYearFraction(date):
"""Converts :class:`datetime.date` or :class:`datetime.datetime` to decimal
year.
Parameters
==========
date : :class:`datetime.date` or :class:`datetime.datetime`
Returns
=======
year : float
Decimal year
Notes
=====
The algorithm is take... | Converts :class:`datetime.date` or :class:`datetime.datetime` to decimal
year.
Parameters
==========
date : :class:`datetime.date` or :class:`datetime.datetime`
Returns
=======
year : float
Decimal year
Notes
=====
The algorithm is taken from http://stackoverflow.com/a... | entailment |
def gc2gdlat(gclat):
"""Converts geocentric latitude to geodetic latitude using WGS84.
Parameters
==========
gclat : array_like
Geocentric latitude
Returns
=======
gdlat : ndarray or float
Geodetic latitude
"""
WGS84_e2 = 0.006694379990141317 # WGS84 first eccentr... | Converts geocentric latitude to geodetic latitude using WGS84.
Parameters
==========
gclat : array_like
Geocentric latitude
Returns
=======
gdlat : ndarray or float
Geodetic latitude | entailment |
def subsol(datetime):
"""Finds subsolar geocentric latitude and longitude.
Parameters
==========
datetime : :class:`datetime.datetime`
Returns
=======
sbsllat : float
Latitude of subsolar point
sbsllon : float
Longitude of subsolar point
Notes
=====
Based o... | Finds subsolar geocentric latitude and longitude.
Parameters
==========
datetime : :class:`datetime.datetime`
Returns
=======
sbsllat : float
Latitude of subsolar point
sbsllon : float
Longitude of subsolar point
Notes
=====
Based on formulas in Astronomical Al... | entailment |
def make_auth_headers():
"""Make the authentication headers needed to use the Appveyor API."""
if not os.path.exists(".appveyor.token"):
raise RuntimeError(
"Please create a file named `.appveyor.token` in the current directory. "
"You can get the token from https://ci.appveyor.c... | Make the authentication headers needed to use the Appveyor API. | entailment |
def get_project_build(account_project):
"""Get the details of the latest Appveyor build."""
url = make_url("/projects/{account_project}", account_project=account_project)
response = requests.get(url, headers=make_auth_headers())
return response.json() | Get the details of the latest Appveyor build. | entailment |
def download_url(url, filename, headers):
"""Download a file from `url` to `filename`."""
ensure_dirs(filename)
response = requests.get(url, headers=headers, stream=True)
if response.status_code == 200:
with open(filename, 'wb') as f:
for chunk in response.iter_content(16 * 1024):
... | Download a file from `url` to `filename`. | entailment |
def cli_schemata_list(self, *args):
"""Display a list of registered schemata"""
self.log('Registered schemata languages:', ",".join(sorted(l10n_schemastore.keys())))
self.log('Registered Schemata:', ",".join(sorted(schemastore.keys())))
if '-c' in args or '-config' in args:
... | Display a list of registered schemata | entailment |
def cli_form(self, *args):
"""Display a schemata's form definition"""
if args[0] == '*':
for schema in schemastore:
self.log(schema, ':', schemastore[schema]['form'], pretty=True)
else:
self.log(schemastore[args[0]]['form'], pretty=True) | Display a schemata's form definition | entailment |
def cli_schema(self, *args):
"""Display a single schema definition"""
key = None
if len(args) > 1:
key = args[1]
args = list(args)
if '-config' in args or '-c' in args:
store = configschemastore
try:
args.remove('-c')
... | Display a single schema definition | entailment |
def cli_forms(self, *args):
"""List all available form definitions"""
forms = []
missing = []
for key, item in schemastore.items():
if 'form' in item and len(item['form']) > 0:
forms.append(key)
else:
missing.append(key)
... | List all available form definitions | entailment |
def cli_default_perms(self, *args):
"""Show default permissions for all schemata"""
for key, item in schemastore.items():
# self.log(item, pretty=True)
if item['schema'].get('no_perms', False):
self.log('Schema without permissions:', key)
continue... | Show default permissions for all schemata | entailment |
def ready(self):
"""Sets up the application after startup."""
self.log('Got', len(schemastore), 'data and',
len(configschemastore), 'component schemata.', lvl=debug) | Sets up the application after startup. | entailment |
def all(self, event):
"""Return all known schemata to the requesting client"""
self.log("Schemarequest for all schemata from",
event.user, lvl=debug)
response = {
'component': 'hfos.events.schemamanager',
'action': 'all',
'data': l10n_schemas... | Return all known schemata to the requesting client | entailment |
def get(self, event):
"""Return a single schema"""
self.log("Schemarequest for", event.data, "from",
event.user, lvl=debug)
if event.data in schemastore:
response = {
'component': 'hfos.events.schemamanager',
'action': 'get',
... | Return a single schema | entailment |
def configuration(self, event):
"""Return all configurable components' schemata"""
try:
self.log("Schemarequest for all configuration schemata from",
event.user.account.name, lvl=debug)
response = {
'component': 'hfos.events.schemamanager',
... | Return all configurable components' schemata | entailment |
def uuid_object(title="Reference", description="Select an object", default=None, display=True):
"""Generates a regular expression controlled UUID field"""
uuid = {
'pattern': '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{'
'4}-['
'a-fA-F0-9]{4}-[a-fA-F0-9]{12}$',
... | Generates a regular expression controlled UUID field | entailment |
def base_object(name,
no_perms=False,
has_owner=True,
hide_owner=True,
has_uuid=True,
roles_write=None,
roles_read=None,
roles_list=None,
roles_create=None,
all_roles=None):
... | Generates a basic object with RBAC properties | 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 sensordata(self, event):
"""
Generates a new reference frame from incoming sensordata
:param event: new sensordata to be merged into referenceframe
"""
if len(self.datatypes) == 0:
return
data = event.data
timestamp = event.timestamp
# b... | Generates a new reference frame from incoming sensordata
:param event: new sensordata to be merged into referenceframe | entailment |
def navdatapush(self):
"""
Pushes the current :referenceframe: out to clients.
:return:
"""
try:
self.fireEvent(referenceframe({
'data': self.referenceframe, 'ages': self.referenceages
}), "navdata")
self.intervalcount += 1
... | Pushes the current :referenceframe: out to clients.
:return: | entailment |
def db_export(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit):
"""Export stored objects
Warning! This functionality is work in progress and you may destroy live data by using it!
Be very careful when using the export/import functionality!"""
internal_backup(schema, uu... | Export stored objects
Warning! This functionality is work in progress and you may destroy live data by using it!
Be very careful when using the export/import functionality! | entailment |
def db_import(ctx, schema, uuid, object_filter, import_format, filename, all_schemata, dry):
"""Import objects from file
Warning! This functionality is work in progress and you may destroy live data by using it!
Be very careful when using the export/import functionality!"""
import_format = import_form... | Import objects from file
Warning! This functionality is work in progress and you may destroy live data by using it!
Be very careful when using the export/import functionality! | entailment |
def _page_update(self, event):
"""
Checks if the newly created object is a wikipage..
If so, rerenders the automatic index.
:param event: objectchange or objectcreation event
"""
try:
if event.schema == 'wikipage':
self._update_index()
... | Checks if the newly created object is a wikipage..
If so, rerenders the automatic index.
:param event: objectchange or objectcreation event | entailment |
def drop_privileges(uid_name='hfos', gid_name='hfos'):
"""Attempt to drop privileges and change user to 'hfos' user/group"""
if os.getuid() != 0:
hfoslog("Not root, cannot drop privileges", lvl=warn, emitter='CORE')
return
try:
# Get the uid/gid from the name
running_uid = ... | Attempt to drop privileges and change user to 'hfos' user/group | entailment |
def construct_graph(args):
"""Preliminary HFOS application Launcher"""
app = Core(args)
setup_root(app)
if args['debug']:
from circuits import Debugger
hfoslog("Starting circuits debugger", lvl=warn, emitter='GRAPH')
dbg = Debugger().register(app)
# TODO: Make these co... | Preliminary HFOS application Launcher | entailment |
def launch(run=True, **args):
"""Bootstrap basics, assemble graph and hand over control to the Core
component"""
verbosity['console'] = args['log'] if not args['quiet'] else 100
verbosity['global'] = min(args['log'], args['logfileverbosity'])
verbosity['file'] = args['logfileverbosity'] if args['do... | Bootstrap basics, assemble graph and hand over control to the Core
component | entailment |
def ready(self, source):
"""All components have initialized, set up the component
configuration schema-store, run the local server and drop privileges"""
from hfos.database import configschemastore
configschemastore[self.name] = self.configschema
self._start_server()
i... | All components have initialized, set up the component
configuration schema-store, run the local server and drop privileges | entailment |
def trigger_frontend_build(self, event):
"""Event hook to trigger a new frontend build"""
from hfos.database import instance
install_frontend(instance=instance,
forcerebuild=event.force,
install=event.install,
developmen... | Event hook to trigger a new frontend build | entailment |
def cli_reload(self, event):
"""Experimental call to reload the component tree"""
self.log('Reloading all components.')
self.update_components(forcereload=True)
initialize()
from hfos.debugger import cli_compgraph
self.fireEvent(cli_compgraph()) | Experimental call to reload the component tree | entailment |
def cli_info(self, event):
"""Provides information about the running instance"""
self.log('Instance:', self.instance,
'Dev:', self.development,
'Host:', self.host,
'Port:', self.port,
'Insecure:', self.insecure,
'Front... | Provides information about the running instance | entailment |
def _start_server(self, *args):
"""Run the node local server"""
self.log("Starting server", args)
secure = self.certificate is not None
if secure:
self.log("Running SSL server with cert:", self.certificate)
else:
self.log("Running insecure server without ... | Run the node local server | entailment |
def update_components(self, forcereload=False, forcerebuild=False,
forcecopy=True, install=False):
"""Check all known entry points for components. If necessary,
manage configuration updates"""
# TODO: See if we can pull out major parts of the component handling.
... | Check all known entry points for components. If necessary,
manage configuration updates | entailment |
def _start_frontend(self, restart=False):
"""Check if it is enabled and start the frontend http & websocket"""
self.log(self.config, self.config.frontendenabled, lvl=verbose)
if self.config.frontendenabled and not self.frontendrunning or restart:
self.log("Restarting webfrontend ser... | Check if it is enabled and start the frontend http & websocket | entailment |
def _instantiate_components(self, clear=True):
"""Inspect all loadable components and run them"""
if clear:
import objgraph
from copy import deepcopy
from circuits.tools import kill
from circuits import Component
for comp in self.runningcompon... | Inspect all loadable components and run them | entailment |
def started(self, component):
"""Sets up the application after startup."""
self.log("Running.")
self.log("Started event origin: ", component, lvl=verbose)
populate_user_events()
from hfos.events.system import AuthorizedEvents
self.log(len(AuthorizedEvents), "authorized ... | Sets up the application after startup. | entailment |
def user(ctx, username, password):
"""[GROUP] User management operations"""
ctx.obj['username'] = username
ctx.obj['password'] = password | [GROUP] User management operations | entailment |
def _create_user(ctx):
"""Internal method to create a normal user"""
username, passhash = _get_credentials(ctx.obj['username'],
ctx.obj['password'],
ctx.obj['db'])
if ctx.obj['db'].objectmodels['user'].count({'name': usern... | Internal method to create a normal user | entailment |
def create_user(ctx):
"""Creates a new local user"""
try:
new_user = _create_user(ctx)
new_user.save()
log("Done")
except KeyError:
log('User already exists', lvl=warn) | Creates a new local user | entailment |
def create_admin(ctx):
"""Creates a new local user and assigns admin role"""
try:
admin = _create_user(ctx)
admin.roles.append('admin')
admin.save()
log("Done")
except KeyError:
log('User already exists', lvl=warn) | Creates a new local user and assigns admin role | entailment |
def delete_user(ctx, yes):
"""Delete a local user"""
if ctx.obj['username'] is None:
username = _ask("Please enter username:")
else:
username = ctx.obj['username']
del_user = ctx.obj['db'].objectmodels['user'].find_one({'name': username})
if yes or _ask('Confirm deletion', default=... | Delete a local user | entailment |
def change_password(ctx):
"""Change password of an existing user"""
username, passhash = _get_credentials(ctx.obj['username'],
ctx.obj['password'],
ctx.obj['db'])
change_user = ctx.obj['db'].objectmodels['user'].find_one({... | Change password of an existing user | entailment |
def list_users(ctx, search, uuid, active):
"""List all locally known users"""
users = ctx.obj['db'].objectmodels['user']
for found_user in users.find():
if not search or (search and search in found_user.name):
# TODO: Not 2.x compatible
print(found_user.name, end=' ' if act... | List all locally known users | entailment |
def disable(ctx):
"""Disable an existing user"""
if ctx.obj['username'] is None:
log('Specify the username with "iso db user --username ..."')
return
change_user = ctx.obj['db'].objectmodels['user'].find_one({
'name': ctx.obj['username']
})
change_user.active = False
c... | Disable an existing user | entailment |
def enable(ctx):
"""Enable an existing user"""
if ctx.obj['username'] is None:
log('Specify the username with "iso db user --username ..."')
return
change_user = ctx.obj['db'].objectmodels['user'].find_one({
'name': ctx.obj['username']
})
change_user.active = True
chan... | Enable an existing user | entailment |
def add_role(ctx, role):
"""Grant a role to an existing user"""
if role is None:
log('Specify the role with --role')
return
if ctx.obj['username'] is None:
log('Specify the username with --username')
return
change_user = ctx.obj['db'].objectmodels['user'].find_one({
... | Grant a role to an existing user | entailment |
def check_expression(testing_framework, expression_dict):
"""
>>> class mock_framework:
... def assertIn(self, item, list, msg="Failed asserting item is in list"):
... if item not in list: raise Exception(msg)
... def assertTrue(self, value, msg="Failed asserting true"):
... if not v... | >>> class mock_framework:
... def assertIn(self, item, list, msg="Failed asserting item is in list"):
... if item not in list: raise Exception(msg)
... def assertTrue(self, value, msg="Failed asserting true"):
... if not value: raise Exception(msg)
... def assertFalse(self, value, msg)... | entailment |
def _get_future_tasks(self):
"""Assemble a list of future alerts"""
self.alerts = {}
now = std_now()
for task in objectmodels['task'].find({'alert_time': {'$gt': now}}):
self.alerts[task.alert_time] = task
self.log('Found', len(self.alerts), 'future tasks') | Assemble a list of future alerts | entailment |
def check_alerts(self):
"""Periodical check to issue due alerts"""
alerted = []
for alert_time, task in self.alerts.items():
task_time = dateutil.parser.parse(alert_time)
if task_time < get_time():
self.log('Alerting about task now:', task)
... | Periodical check to issue due alerts | entailment |
def read(self, data):
"""Handles incoming raw sensor data and broadcasts it to specified
udp servers and connected tcp clients
:param data: NMEA raw sentences incoming data
"""
self.log('Received NMEA data:', data, lvl=debug)
# self.log(data, pretty=True)
if sel... | Handles incoming raw sensor data and broadcasts it to specified
udp servers and connected tcp clients
:param data: NMEA raw sentences incoming data | entailment |
def cmdmap(xdot):
"""Generates a command map"""
# TODO: Integrate the output into documentation
from copy import copy
def print_commands(command, map_output, groups=None, depth=0):
if groups is None:
groups = []
if 'commands' in command.__dict__:
if len(groups) ... | Generates a command map | entailment |
def format_template(template, content):
"""Render a given pystache template
with given content"""
import pystache
result = u""
if True: # try:
result = pystache.render(template, content, string_encoding='utf-8')
# except (ValueError, KeyError) as e:
# print("Templating error: %s... | Render a given pystache template
with given content | entailment |
def format_template_file(filename, content):
"""Render a given pystache template file with given content"""
with open(filename, 'r') as f:
template = f.read()
if type(template) != str:
template = template.decode('utf-8')
return format_template(template, content) | Render a given pystache template file with given content | entailment |
def write_template_file(source, target, content):
"""Write a new file from a given pystache template file and content"""
# print(formatTemplateFile(source, content))
print(target)
data = format_template_file(source, content)
with open(target, 'w') as f:
for line in data:
if type... | Write a new file from a given pystache template file and content | entailment |
def insert_nginx_service(definition): # pragma: no cover
"""Insert a new nginx service definition"""
config_file = '/etc/nginx/sites-available/hfos.conf'
splitter = "### SERVICE DEFINITIONS ###"
with open(config_file, 'r') as f:
old_config = "".join(f.readlines())
pprint(old_config)
... | Insert a new nginx service definition | entailment |
def rbac(ctx, schema, object_filter, action, role, all_schemata):
"""[GROUP] Role based access control"""
database = ctx.obj['db']
if schema is None:
if all_schemata is False:
log('No schema given. Read the RBAC group help', lvl=warn)
sys.exit()
else:
sc... | [GROUP] Role based access control | entailment |
def add_action_role(ctx):
"""Adds a role to an action on objects"""
objects = ctx.obj['objects']
action = ctx.obj['action']
role = ctx.obj['role']
if action is None or role is None:
log('You need to specify an action or role to the RBAC command group for this to work.', lvl=warn)
r... | Adds a role to an action on objects | entailment |
def del_action_role(ctx):
"""Deletes a role from an action on objects"""
objects = ctx.obj['objects']
action = ctx.obj['action']
role = ctx.obj['role']
if action is None or role is None:
log('You need to specify an action or role to the RBAC command group for this to work.', lvl=warn)
... | Deletes a role from an action on objects | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.