code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self._check_fix_users(username)
current_groups = self.users[username]['groups']
new_groups = current_groups | set(groups)
self.users[username]['groups'] = new_groups | def add_to_groups(self, username, groups) | Add a user to a list of groups
:param username: 'key' attribute of the user
:type username: string
:param groups: list of groups
:type groups: list of strings | 3.468252 | 3.810173 | 0.910261 |
ret = {}
for user in self.users:
match = False
for attr in self.search_attrs:
if attr not in self.users[user]:
pass
elif re.search(searchstring + '.*', self.users[user][attr]):
match = True
... | def search(self, searchstring) | Search backend for users
:param searchstring: the search string
:type searchstring: string
:rtype: dict of dict ( {<user attr key>: {<attr>: <value>}} ) | 2.781992 | 2.620888 | 1.061469 |
try:
return self.users[username]
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | def get_user(self, username) | Get a user's attributes
:param username: 'key' attribute of the user
:type username: string
:rtype: dict ( {<attr>: <value>} )
.. warning:: raise UserDoesntExist if user doesn't exist | 4.894313 | 4.781328 | 1.023631 |
try:
return self.users[username]['groups']
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | def get_groups(self, username) | Get a user's groups
:param username: 'key' attribute of the user
:type username: string
:rtype: list of groups | 5.451181 | 6.035881 | 0.903129 |
if level == 'debug':
return logging.DEBUG
elif level == 'notice':
return logging.INFO
elif level == 'info':
return logging.INFO
elif level == 'warning' or level == 'warn':
return logging.WARNING
elif level == 'error' or level == 'err':
return logging.ERRO... | def get_loglevel(level) | return logging level object
corresponding to a given level passed as
a string
@str level: name of a syslog log level
@rtype: logging, logging level from logging module | 1.500134 | 1.555908 | 0.964153 |
et = type(e)
if et is ldap.OPERATIONS_ERROR:
self._logger(
severity=logging.ERROR,
msg="cannot use starttls with ldaps://"
" uri (uri: " + self.uri + ")",
)
elif et is ldap.INVALID_CREDENTIALS:
self.... | def _exception_handler(self, e) | Exception handling | 3.00958 | 2.990961 | 1.006225 |
class AccessSaver:
def __init__(self):
self.keys = []
def __getitem__(self, key):
self.keys.append(key)
a = AccessSaver()
fmt_string % a
return a.keys | def _extract_format_keys(self, fmt_string) | Extract the keys of a format string
(the 'stuff' in '%(stuff)s' | 4.469031 | 4.102936 | 1.089228 |
for key in self.group_attrs_keys:
if key not in attrs:
raise MissingGroupAttr(key)
if type(attrs[key]) is list and len(attrs[key]) == 1:
attrs[key] = attrs[key][0]
if type(attrs[key]) is list and len(attrs[key]) != 1:
r... | def _normalize_group_attrs(self, attrs) | Normalize the attributes used to set groups
If it's a list of one element, it just become this
element.
It raises an error if the attribute doesn't exist
or if it's multivaluated. | 2.307237 | 2.036518 | 1.132932 |
ldap_client = ldap.initialize(self.uri)
ldap.set_option(ldap.OPT_REFERRALS, 0)
ldap.set_option(ldap.OPT_TIMEOUT, self.timeout)
if self.starttls == 'on':
ldap.set_option(ldap.OPT_X_TLS_DEMAND, True)
else:
ldap.set_option(ldap.OPT_X_TLS_DEMAND, Fals... | def _connect(self) | Initialize an ldap client | 2.84481 | 2.738674 | 1.038754 |
ldap_client = self._connect()
try:
ldap_client.simple_bind_s(self.binddn, self.bindpassword)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
return ldap_client | def _bind(self) | bind to the ldap with the technical account | 3.414512 | 2.830578 | 1.206295 |
if attrs == NO_ATTR:
attrlist = []
elif attrs == DISPLAYED_ATTRS:
# fix me later (to much attributes)
attrlist = self.attrlist
elif attrs == LISTED_ATTRS:
attrlist = self.attrlist
elif attrs == ALL_ATTRS:
attrlist = Non... | def _search(self, searchfilter, attrs, basedn) | Generic search | 3.280499 | 3.278357 | 1.000653 |
username = ldap.filter.escape_filter_chars(username)
user_filter = self.user_filter_tmpl % {
'username': self._uni(username)
}
r = self._search(self._byte_p2(user_filter), attrs, self.userdn)
if len(r) == 0:
return None
# if NO_ATTR, on... | def _get_user(self, username, attrs=ALL_ATTRS) | Get a user from the ldap | 5.264557 | 5.035319 | 1.045526 |
binddn = self._get_user(self._byte_p2(username), NO_ATTR)
if binddn is not None:
ldap_client = self._connect()
try:
ldap_client.simple_bind_s(
self._byte_p2(binddn),
self._byte_p2(password)
... | def auth(self, username, password) | Authentication of a user | 3.614805 | 3.566687 | 1.013491 |
ldap_client = self._bind()
# encoding crap
attrs_srt = self.attrs_pretreatment(attrs)
attrs_srt[self._byte_p2('objectClass')] = self.objectclasses
# construct is DN
dn = \
self._byte_p2(self.dn_user_attr) + \
self._byte_p2('=') + \
... | def add_user(self, attrs) | add a user | 4.820094 | 4.760201 | 1.012582 |
ldap_client = self._bind()
# recover the user dn
dn = self._byte_p2(self._get_user(self._byte_p2(username), NO_ATTR))
# delete
if dn is not None:
ldap_client.delete_s(dn)
else:
ldap_client.unbind_s()
raise UserDoesntExist(usern... | def del_user(self, username) | delete a user | 5.844761 | 5.889486 | 0.992406 |
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = self._byte_p2(tmp[0])
old_attrs = tmp[1]
for attr in attrs:
bcontent = self._byte_p... | def set_attrs(self, username, attrs) | set user attributes | 3.623 | 3.592023 | 1.008624 |
# it follows the same logic than add_to_groups
# but with MOD_DELETE
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = tmp[0]
attrs = tmp... | def del_from_groups(self, username, groups) | Delete user from groups | 3.817672 | 3.799444 | 1.004797 |
# escape special char to avoid injection
searchstring = ldap.filter.escape_filter_chars(
self._byte_p2(searchstring)
)
# fill the search string template
searchfilter = self.search_filter_tmpl % {
'searchstring': searchstring
}
ret... | def search(self, searchstring) | Search users | 4.865734 | 4.89275 | 0.994478 |
ret = {}
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
attrs_tmp = tmp[1]
for attr in attrs_tmp:
value_tmp = attrs_tmp[attr]
if len(value_tmp) == 1:
... | def get_user(self, username) | Gest a specific user | 3.9044 | 3.975202 | 0.982189 |
username = ldap.filter.escape_filter_chars(self._byte_p2(username))
userdn = self._get_user(username, NO_ATTR)
searchfilter = self.group_filter_tmpl % {
'userdn': userdn,
'username': username
}
groups = self._search(searchfilter, NO_ATTR, self.g... | def get_groups(self, username) | Get all groups of a user | 5.315054 | 5.338773 | 0.995557 |
ret = {}
for backends in backends_list:
for b in backends:
if b not in ret:
ret[b] = set([])
for group in backends[b]:
ret[b].add(group)
for b in ret:
ret[b] = list(ret[b])
ret[b]... | def _merge_groups(self, backends_list) | merge a list backends_groups | 2.126505 | 2.052552 | 1.03603 |
if roles is None:
roles_in = copy.deepcopy(self.roles_raw)
else:
roles_in = roles
for roleid in roles_in:
role = roles_in[roleid]
if groups is not None:
role['backends_groups'] = self._merge_groups(
[rol... | def _flatten(self, roles=None, groups=None) | flatten a (semi) nest roles structure | 3.410924 | 3.300316 | 1.033514 |
role2 = copy.deepcopy(self.flatten[roleid2])
role1 = copy.deepcopy(self.flatten[roleid1])
if role1 == role2:
return False
# Check if role1 is contained by role2
for b1 in role1['backends_groups']:
if b1 not in role2['backends_groups']:
... | def _is_parent(self, roleid1, roleid2) | Test if roleid1 is contained inside roleid2 | 2.93439 | 2.789141 | 1.052077 |
self._flatten()
parent_roles = {}
for roleid in self.flatten:
role = copy.deepcopy(self.flatten[roleid])
# Display name is mandatory
if 'display_name' not in role:
raise MissingKey('display_name', role, self.role_file)
if... | def _nest(self) | nests the roles (creates roles hierarchy) | 2.540426 | 2.450514 | 1.036691 |
current_roles = set(current_roles)
ret = {}
roles_to_remove = set(roles_to_remove)
tmp = set([])
# get sub roles of the role to remove that the user belongs to
# if we remove a role, there is no reason to keep the sub roles
for r in roles_to_remove:
... | def get_groups_to_remove(self, current_roles, roles_to_remove) | get groups to remove from list of
roles to remove and current roles | 3.004013 | 2.99402 | 1.003338 |
roles = set([])
parentroles = set([])
notroles = set([])
tmp = set([])
usedgroups = {}
unusedgroups = {}
ret = {}
# determine roles membership
for role in self.roles:
if self._check_member(
role, groups, not... | def get_roles(self, groups) | get list of roles and list of standalone groups | 4.251266 | 3.820315 | 1.112805 |
if role not in self.flatten:
raise MissingRole(role)
return self.flatten[role]['display_name'] | def get_display_name(self, role) | get the display name of a role | 6.401436 | 5.228802 | 1.224264 |
ret = {}
for role in roles:
if role not in self.flatten:
raise MissingRole(role)
for b in self.flatten[role]['backends_groups']:
if b not in ret:
ret[b] = []
ret[b] = ret[b] + self.flatten[role]['backend... | def get_groups(self, roles) | get the list of groups from role | 3.368584 | 3.369494 | 0.99973 |
for r in roles:
if r in self.admin_roles:
return True
return False | def is_admin(self, roles) | determine from a list of roles if is ldapcherry administrator | 3.321467 | 3.068578 | 1.082413 |
if section in config and key in config[section]:
return config[section][key]
if default is not None:
return default
else:
raise MissingParameter(section, key) | def _get_param(self, section, key, config, default=None) | Get configuration parameter "key" from config
@str section: the section of the config file
@str key: the key to get
@dict config: the configuration (dictionnary)
@str default: the default value if parameter "key" is not present
@rtype: str (value of config['key'] if present defau... | 2.598399 | 3.182229 | 0.816534 |
ret = {}
for b in self.backends:
ret[b] = self.backends[b].get_groups(username)
cherrypy.log.error(
msg="user '" + username + "' groups: " + str(ret),
severity=logging.DEBUG,
)
return ret | def _get_groups(self, username) | Get groups of a user
@str username: name of the user
@rtype: dict, format { '<backend>': [<list of groups>] } | 4.527663 | 3.663207 | 1.235983 |
groups = self._get_groups(username)
user_roles = self.roles.get_roles(groups)
cherrypy.log.error(
msg="user '" + username + "' roles: " + str(user_roles),
severity=logging.DEBUG,
)
return user_roles | def _get_roles(self, username) | Get roles of a user
@str username: name of the user
@rtype: dict, format { 'roles': [<list of roles>],
'unusedgroups': [<list of groups not matching roles>] } | 4.196783 | 4.325834 | 0.970167 |
roles = self._get_roles(username)
return self.roles.is_admin(roles['roles']) | def _is_admin(self, username) | Check if a user is an ldapcherry administrator
@str username: name of the user
@rtype: bool, True if administrator, False otherwise | 6.548301 | 7.515438 | 0.871313 |
backends = self.backends_params.keys()
for b in self.roles.get_backends():
if b not in backends:
raise MissingBackend(b, 'role')
for b in self.attributes.get_backends():
if b not in backends:
raise MissingBackend(b, 'attribute') | def _check_backends(self) | Check that every backend in roles and attributes
is declared in main configuration | 3.692199 | 2.95225 | 1.250639 |
self.backends_params = {}
self.backends = {}
self.backends_display_names = {}
for entry in config['backends']:
# split at the first dot
backend, sep, param = entry.partition('.')
value = config['backends'][entry]
if backend not in ... | def _init_backends(self, config) | Init all backends
@dict: configuration of ldapcherry | 2.835298 | 2.79969 | 1.012719 |
self.auth_mode = self._get_param('auth', 'auth.mode', config)
if self.auth_mode in ['and', 'or', 'none']:
pass
elif self.auth_mode == 'custom':
# load custom auth module
auth_module = self._get_param('auth', 'auth.module', config)
auth = _... | def _init_auth(self, config) | Init authentication
@dict: configuration of ldapcherry | 2.947927 | 2.960658 | 0.9957 |
access_handler = self._get_param(
'global',
'log.access_handler',
config,
'syslog',
)
# log format for syslog
syslog_formatter = logging.Formatter(
"ldapcherry[%(process)d]: %(message)s"
)
# re... | def _set_access_log(self, config, level) | Configure access logs | 2.621887 | 2.59941 | 1.008647 |
error_handler = self._get_param(
'global',
'log.error_handler',
config,
'syslog'
)
# log format for syslog
syslog_formatter = logging.Formatter(
"ldapcherry[%(process)d]: %(message)s",
)
# repl... | def _set_error_log(self, config, level, debug=False) | Configure error logs | 3.082188 | 3.058679 | 1.007686 |
if self.auth_mode == 'none':
return {'connected': True, 'isadmin': True}
elif self.auth_mode == 'and':
ret1 = True
for b in self.backends:
ret1 = self.backends[b].auth(user, password) and ret1
elif self.auth_mode == 'or':
r... | def _auth(self, user, password) | authenticate a user
@str user: login of the user
@str password: password of the user
@rtype: dict, {'connected': <boolean, True if connection succeded>,
'isadmin': <True if user is ldapcherry administrator>} | 2.246524 | 2.082325 | 1.078854 |
# definition of the template directory
self.template_dir = self._get_param(
'resources',
'templates.dir',
config
)
cherrypy.log.error(
msg="loading templates from dir '%(dir)s'" %
{'dir': self.template_dir},
... | def _load_templates(self, config) | load templates
@dict: configuration of ldapcherry | 4.223973 | 4.143967 | 1.019307 |
try:
# log configuration handling
# get log level
# (if not in configuration file, log level is set to debug)
level = get_loglevel(
self._get_param(
'global',
'log.level',
config,... | def reload(self, config=None, debug=False) | load/reload configuration
@dict: configuration of ldapcherry | 3.817324 | 3.709088 | 1.029181 |
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username not in self.notifications:
self.notifications[username] = []
self.notifications[username].append(message) | def _add_notification(self, message) | add a notification in the notification queue of a user | 3.137713 | 3.04369 | 1.030891 |
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username in self.notifications:
ret = self.notifications[username]
else:
ret = []
self.notifications[username] = []
return ret | def _empty_notification(self) | empty and return list of message notification | 3.868916 | 3.592449 | 1.076958 |
for attr in attrs_backend:
if attr in self.attributes.backend_attributes[backend_name]:
attrid = self.attributes.backend_attributes[backend_name][attr]
if attrid not in attrs_out:
attrs_out[attrid] = attrs_backend[attr] | def _merge_user_attrs(self, attrs_backend, attrs_out, backend_name) | merge attributes from one backend search to the attributes dict
output | 2.395339 | 2.371641 | 1.009992 |
if searchstring is None:
return {}
ret = {}
for b in self.backends:
tmp = self.backends[b].search(searchstring)
for u in tmp:
if u not in ret:
ret[u] = {}
self._merge_user_attrs(tmp[u], ret[u], b)
... | def _search(self, searchstring) | search users
@str searchstring: search string
@rtype: dict, {<user>: {<attr>: <value>}} | 3.393727 | 2.872119 | 1.181611 |
if username is None:
return {}
ret = {}
for b in self.backends:
try:
tmp = self.backends[b].get_user(username)
except UserDoesntExist as e:
self._handle_exception(e)
tmp = {}
self._merge_user... | def _get_user(self, username) | get user attributes
@str username: user to get
@rtype: dict, {<attr>: <value>} | 4.641593 | 4.269615 | 1.087122 |
ret = {'attrs': {}, 'roles': {}, 'groups': {}}
for p in params:
# each form attributes is prefixed with type, ex: attr.uidNumber
# separate this prefix from the attribute name
p_type, sep, param = p.partition('.')
if p_type == 'attr':
... | def _parse_params(self, params) | get user attributes
@dict params: form parameters
@rtype: dict, {<type>: {<attr>: <value>}} | 4.267262 | 3.873562 | 1.101638 |
if self.auth_mode == 'none':
return 'anonymous'
username = self._check_session()
if cherrypy.request.query_string == '':
qs = ''
else:
qs = '?' + cherrypy.request.query_string
# Escaped version of the requested URL
quoted_requ... | def _check_auth(self, must_admin, redir_login=True) | check if a user is autheticated and, optionnaly an administrator
if user not authenticated -> redirect to login page (with escaped URL
of the originaly requested page (redirection after login)
if user authenticated, not admin and must_admin enabled -> 403 error
@boolean must_admin: f... | 2.242654 | 2.229311 | 1.005985 |
auth = self._auth(login, password)
cherrypy.session['isadmin'] = auth['isadmin']
cherrypy.session['connected'] = auth['connected']
if auth['connected']:
if auth['isadmin']:
message = \
"login success for user '%(user)s' as adminis... | def login(self, login, password, url=None) | login page | 2.425228 | 2.447092 | 0.991065 |
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
sess[SESSION_KEY] = None
if username:
cherrypy.request.login = None
cherrypy.log.error(
msg="user '%(user)s' logout" % {'user': username},
severity=logging.INFO
)
... | def logout(self) | logout page | 3.940221 | 3.772435 | 1.044477 |
self._check_auth(must_admin=False)
is_admin = self._check_admin()
sess = cherrypy.session
user = sess.get(SESSION_KEY, None)
if self.auth_mode == 'none':
user_attrs = None
else:
user_attrs = self._get_user(user)
attrs_list = self.a... | def index(self) | main page rendering | 5.84143 | 5.742408 | 1.017244 |
self._check_auth(must_admin=False)
is_admin = self._check_admin()
if searchstring is not None and len(searchstring) > 2:
res = self._search(searchstring)
else:
res = None
attrs_list = self.attributes.get_search_attributes()
return self.tem... | def searchuser(self, searchstring=None) | search user page | 5.072459 | 5.038783 | 1.006683 |
self._check_auth(must_admin=False, redir_login=False)
keys = list(params.keys())
if len(keys) != 1:
cherrypy.response.status = 400
return "bad argument"
password = params[keys[0]]
is_admin = self._check_admin()
ret = self._checkppolicy(pas... | def checkppolicy(self, **params) | search user page | 3.743765 | 3.590168 | 1.042783 |
self._check_auth(must_admin=True)
is_admin = self._check_admin()
if searchstring is not None:
res = self._search(searchstring)
else:
res = None
attrs_list = self.attributes.get_search_attributes()
return self.temp['searchadmin.tmpl'].rende... | def searchadmin(self, searchstring=None) | search user page | 5.214959 | 5.141275 | 1.014332 |
self._check_auth(must_admin=True)
is_admin = self._check_admin()
if cherrypy.request.method.upper() == 'POST':
params = self._parse_params(params)
self._adduser(params)
self._add_notification("User added")
graph = {}
for r in self.ro... | def adduser(self, **params) | add user page | 3.418829 | 3.360218 | 1.017443 |
self._check_auth(must_admin=True)
is_admin = self._check_admin()
try:
referer = cherrypy.request.headers['Referer']
except Exception as e:
referer = '/'
self._deleteuser(user)
self._add_notification('User Deleted')
raise cherrypy.H... | def delete(self, user) | remove user page | 4.905675 | 4.521762 | 1.084903 |
self._check_auth(must_admin=True)
is_admin = self._check_admin()
if cherrypy.request.method.upper() == 'POST':
params = self._parse_params(params)
self._modify(params)
self._add_notification("User modified")
try:
referer =... | def modify(self, user=None, **params) | modify user page | 3.358124 | 3.30772 | 1.015238 |
self._check_auth(must_admin=False)
is_admin = self._check_admin()
sess = cherrypy.session
user = sess.get(SESSION_KEY, None)
if self.auth_mode == 'none':
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning'... | def selfmodify(self, **params) | self modify user page | 4.593213 | 4.502625 | 1.020119 |
sys.path = [''] + sys.path
# monkey patching cherrypy to disable config interpolation
def new_as_dict(self, raw=True, vars=None):
# Load INI file into a dict
result = {}
for section in self.sections():
if section not in result:
result[sectio... | def start(configfile=None, daemonize=False, environment=None,
fastcgi=False, scgi=False, pidfile=None,
cgi=False, debug=False) | Subscribe all engine plugins and start the engine. | 3.258735 | 3.267198 | 0.99741 |
preview_outputs = []
file_outputs = []
bast_ctx = context
added = set()
for output_group, output_files in context['job_info']['file_groups'].items():
for output_file_content in output_files:
if output_group:
bast_ctx.updat... | def render_to_response(self, context, *args, **kwargs) | Build dictionary of content | 2.75295 | 2.735053 | 1.006543 |
if not request.is_ajax():
return HttpResponseForbidden()
try:
app, model, pk = request.POST['app'], request.POST['model'], int(request.POST['pk'])
except ValueError:
return HttpResponseBadRequest()
try:
ctype = ContentType.objects.get(app_label=app, model=model)
... | def toggle_favorite(request) | Add/remove an object to the user's favorites. Checks for existance and adds if not, else removes.
This is the underlying mechanism for adding items to the user 'scrapbook' and favorite scripts.
:param request:
:param file_id:
:return: | 2.011762 | 2.146403 | 0.937271 |
from .models import WooeyJob
# Get active tasks from Celery
inspect = celery_app.control.inspect()
active_tasks = {task['id'] for worker, tasks in six.iteritems(inspect.active()) for task in tasks}
# find jobs that are marked as running but not present in celery's active tasks
active_jobs... | def cleanup_dead_jobs() | This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant
to cleanup jobs that have been lost due to a server crash or some other reason a job is
in limbo. | 3.298931 | 3.082319 | 1.070276 |
ct = ContentType.objects.get_for_model(obj)
return '%s-%s-%s' % (ct.app_label, ct.model, obj.id) | def app_model_id(obj) | Returns a app-model-id string for a given object
:param obj:
:return: | 2.793427 | 2.914769 | 0.95837 |
form_field = param.form_field
widget_data_dict = {}
appender_data_dict = {}
widget_init = {}
WOOEY_CHOICE_LIMIT = 'data-wooey-choice-limit'
choices = json.loads(param.choices)
field_kwargs = {
'label': param.script_param.replace('_', ' ').titl... | def get_field(param, initial=None) | Any extra field attributes for the widget for customization of Wooey at the field level
can be added to the widget dictionary, widget_data_dict, or to the appender_data_dict, which
is the little plus button. This is useful since there is only a single copy of the plus,
whereas we can have mul... | 2.804105 | 2.706192 | 1.036181 |
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] | def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub) | Split the query string into individual keywords, discarding spaces
and grouping quoted words together.
>>> normalize_query(' some random words "with quotes " and spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces'] | 1.687969 | 3.472182 | 0.486141 |
super(ModelDiffMixin, self).save(*args, **kwargs)
self.__initial = self._dict | def save(self, *args, **kwargs) | Saves model and set initial state. | 10.030588 | 8.017448 | 1.251095 |
text_pixels = self.load_image(text_image_file, False)
with open(text_file, 'r') as f:
loaded_text = f.read()
self._text_dict = {}
for index, s in enumerate(loaded_text):
start = index * 40
end = start + 40
char = text_pixels[start... | def _load_text_assets(self, text_image_file, text_file) | Internal. Builds a character indexed dictionary of pixels used by the
show_message function below | 2.91763 | 2.679857 | 1.088726 |
is_empty = True
while is_empty: # From front
row = char[0:8]
is_empty = psum(row) == 0
if is_empty:
del char[0:8]
is_empty = True
while is_empty: # From back
row = char[-8:]
... | def _trim_whitespace(self, char): # For loading text assets only
psum = lambda x: sum(sum(x, []))
if psum(char) > 0 | Internal. Trims white space pixels from the front and back of loaded
text characters | 2.8275 | 2.8047 | 1.008129 |
ini_file = '%s.ini' % imu_settings_file
home_dir = pwd.getpwuid(os.getuid())[5]
home_path = os.path.join(home_dir, self.SETTINGS_HOME_PATH)
if not os.path.exists(home_path):
os.makedirs(home_path)
home_file = os.path.join(home_path, ini_file)
home_... | def _get_settings_file(self, imu_settings_file) | Internal. Logic to check for a system wide RTIMU ini file. This is
copied to the home folder if one is not already found there. | 2.18822 | 2.068187 | 1.058038 |
device = None
for fb in glob.glob('/sys/class/graphics/fb*'):
name_file = os.path.join(fb, 'name')
if os.path.isfile(name_file):
with open(name_file, 'r') as f:
name = f.read()
if name.strip() == self.SENSE_HAT_FB_NAM... | def _get_fb_device(self) | Internal. Finds the correct frame buffer device for the sense HAT
and returns its /dev name. | 2.965363 | 2.403823 | 1.233603 |
if r in self._pix_map.keys():
if redraw:
pixel_list = self.get_pixels()
self._rotation = r
if redraw:
self.set_pixels(pixel_list)
else:
raise ValueError('Rotation must be 0, 90, 180 or 270 degrees') | def set_rotation(self, r=0, redraw=True) | Sets the LED matrix rotation for viewing, adjust if the Pi is upside
down or sideways. 0 is with the Pi HDMI port facing downwards | 3.491813 | 3.13114 | 1.115189 |
r = (pix[0] >> 3) & 0x1F
g = (pix[1] >> 2) & 0x3F
b = (pix[2] >> 3) & 0x1F
bits16 = (r << 11) + (g << 5) + b
return struct.pack('H', bits16) | def _pack_bin(self, pix) | Internal. Encodes python list [R,G,B] into 16 bit RGB565 | 2.257821 | 1.914365 | 1.17941 |
output = struct.unpack('H', packed)
bits16 = output[0]
r = (bits16 & 0xF800) >> 11
g = (bits16 & 0x7E0) >> 5
b = (bits16 & 0x1F)
return [int(r << 3), int(g << 2), int(b << 3)] | def _unpack_bin(self, packed) | Internal. Decodes 16 bit RGB565 into python list [R,G,B] | 2.602712 | 2.214413 | 1.175351 |
pixel_list = self.get_pixels()
flipped = []
for i in range(8):
offset = i * 8
flipped.extend(reversed(pixel_list[offset:offset + 8]))
if redraw:
self.set_pixels(flipped)
return flipped | def flip_h(self, redraw=True) | Flip LED matrix horizontal | 3.033689 | 2.721422 | 1.114744 |
if len(pixel_list) != 64:
raise ValueError('Pixel lists must have 64 elements')
for index, pix in enumerate(pixel_list):
if len(pix) != 3:
raise ValueError('Pixel at index %d is invalid. Pixels must contain 3 elements: Red, Green and Blue' % index)
... | def set_pixels(self, pixel_list) | Accepts a list containing 64 smaller lists of [R,G,B] pixels and
updates the LED matrix. R,G,B elements must intergers between 0
and 255 | 3.243312 | 3.045913 | 1.064808 |
pixel_list = []
with open(self._fb_device, 'rb') as f:
map = self._pix_map[self._rotation]
for row in range(8):
for col in range(8):
# Two bytes per pixel in fb memory, 16 bit RGB565
f.seek(map[row][col] * 2) # ro... | def get_pixels(self) | Returns a list containing 64 smaller lists of [R,G,B] pixels
representing what is currently displayed on the LED matrix | 5.388665 | 4.796865 | 1.123372 |
pixel_error = 'Pixel arguments must be given as (r, g, b) or r, g, b'
if len(args) == 1:
pixel = args[0]
if len(pixel) != 3:
raise ValueError(pixel_error)
elif len(args) == 3:
pixel = args
else:
raise ValueError(p... | def set_pixel(self, x, y, *args) | Updates the single [R,G,B] pixel specified by x and y on the LED matrix
Top left = 0,0 Bottom right = 7,7
e.g. ap.set_pixel(x, y, r, g, b)
or
pixel = (r, g, b)
ap.set_pixel(x, y, pixel) | 2.873376 | 2.683822 | 1.070628 |
if x > 7 or x < 0:
raise ValueError('X position must be between 0 and 7')
if y > 7 or y < 0:
raise ValueError('Y position must be between 0 and 7')
pix = None
with open(self._fb_device, 'rb') as f:
map = self._pix_map[self._rotation]
... | def get_pixel(self, x, y) | Returns a list of [R,G,B] representing the pixel specified by x and y
on the LED matrix. Top left = 0,0 Bottom right = 7,7 | 3.966168 | 3.585805 | 1.106075 |
if not os.path.exists(file_path):
raise IOError('%s not found' % file_path)
img = Image.open(file_path).convert('RGB')
pixel_list = list(map(list, img.getdata()))
if redraw:
self.set_pixels(pixel_list)
return pixel_list | def load_image(self, file_path, redraw=True) | Accepts a path to an 8 x 8 image file and updates the LED matrix with
the image | 2.546072 | 2.497468 | 1.019462 |
black = (0, 0, 0) # default
if len(args) == 0:
colour = black
elif len(args) == 1:
colour = args[0]
elif len(args) == 3:
colour = args
else:
raise ValueError('Pixel arguments must be given as (r, g, b) or r, g, b')
... | def clear(self, *args) | Clears the LED matrix with a single colour, default is black / off
e.g. ap.clear()
or
ap.clear(r, g, b)
or
colour = (r, g, b)
ap.clear(colour) | 3.2565 | 2.596592 | 1.254144 |
if len(s) == 1 and s in self._text_dict.keys():
return list(self._text_dict[s])
else:
return list(self._text_dict['?']) | def _get_char_pixels(self, s) | Internal. Safeguards the character indexed dictionary for the
show_message function below | 3.654603 | 3.021846 | 1.209394 |
# We must rotate the pixel map left through 90 degrees when drawing
# text, see _load_text_assets
previous_rotation = self._rotation
self._rotation -= 90
if self._rotation < 0:
self._rotation = 270
dummy_colour = [None, None, None]
string_pad... | def show_message(
self,
text_string,
scroll_speed=.1,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
) | Scrolls a string of text across the LED matrix using the specified
speed and colours | 3.649328 | 3.661937 | 0.996557 |
if len(s) > 1:
raise ValueError('Only one character may be passed into this method')
# We must rotate the pixel map left through 90 degrees when drawing
# text, see _load_text_assets
previous_rotation = self._rotation
self._rotation -= 90
if self._ro... | def show_letter(
self,
s,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
) | Displays a single text character on the LED matrix using the specified
colours | 3.742833 | 3.609167 | 1.037035 |
with open(self._fb_device) as f:
fcntl.ioctl(f, self.SENSE_HAT_FB_FBIORESET_GAMMA, self.SENSE_HAT_FB_GAMMA_DEFAULT) | def gamma_reset(self) | Resets the LED matrix gamma correction to default | 7.85458 | 6.601353 | 1.189844 |
if not self._humidity_init:
self._humidity_init = self._humidity.humidityInit()
if not self._humidity_init:
raise OSError('Humidity Init Failed') | def _init_humidity(self) | Internal. Initialises the humidity sensor via RTIMU | 5.061452 | 4.452165 | 1.136852 |
if not self._pressure_init:
self._pressure_init = self._pressure.pressureInit()
if not self._pressure_init:
raise OSError('Pressure Init Failed') | def _init_pressure(self) | Internal. Initialises the pressure sensor via RTIMU | 6.07706 | 4.222933 | 1.439061 |
self._init_humidity() # Ensure humidity sensor is initialised
humidity = 0
data = self._humidity.humidityRead()
if (data[0]): # Humidity valid
humidity = data[1]
return humidity | def get_humidity(self) | Returns the percentage of relative humidity | 7.50834 | 6.480908 | 1.158532 |
self._init_humidity() # Ensure humidity sensor is initialised
temp = 0
data = self._humidity.humidityRead()
if (data[2]): # Temp valid
temp = data[3]
return temp | def get_temperature_from_humidity(self) | Returns the temperature in Celsius from the humidity sensor | 9.718269 | 7.781442 | 1.248903 |
self._init_pressure() # Ensure pressure sensor is initialised
temp = 0
data = self._pressure.pressureRead()
if (data[2]): # Temp valid
temp = data[3]
return temp | def get_temperature_from_pressure(self) | Returns the temperature in Celsius from the pressure sensor | 10.68545 | 7.85693 | 1.360003 |
self._init_pressure() # Ensure pressure sensor is initialised
pressure = 0
data = self._pressure.pressureRead()
if (data[0]): # Pressure valid
pressure = data[1]
return pressure | def get_pressure(self) | Returns the pressure in Millibars | 8.924232 | 7.171968 | 1.244321 |
if not self._imu_init:
self._imu_init = self._imu.IMUInit()
if self._imu_init:
self._imu_poll_interval = self._imu.IMUGetPollInterval() * 0.001
# Enable everything on IMU
self.set_imu_config(True, True, True)
else:
... | def _init_imu(self) | Internal. Initialises the IMU sensor via RTIMU | 4.008603 | 3.6069 | 1.111371 |
# If the consuming code always calls this just before reading the IMU
# the IMU consistently fails to read. So prevent unnecessary calls to
# IMU config functions using state variables
self._init_imu() # Ensure imu is initialised
if (not isinstance(compass_enabled, b... | def set_imu_config(self, compass_enabled, gyro_enabled, accel_enabled) | Enables and disables the gyroscope, accelerometer and/or magnetometer
input to the orientation functions | 3.089384 | 3.116235 | 0.991384 |
self._init_imu() # Ensure imu is initialised
attempts = 0
success = False
while not success and attempts < 3:
success = self._imu.IMURead()
attempts += 1
time.sleep(self._imu_poll_interval)
return success | def _read_imu(self) | Internal. Tries to read the IMU sensor three times before giving up | 4.843343 | 3.911677 | 1.238175 |
result = None
if self._read_imu():
data = self._imu.getIMUData()
if data[is_valid_key]:
raw = data[data_key]
result = {
'x': raw[0],
'y': raw[1],
'z': raw[2]
}
... | def _get_raw_data(self, is_valid_key, data_key) | Internal. Returns the specified raw data from the IMU when valid | 3.578375 | 3.259575 | 1.097804 |
raw = self._get_raw_data('fusionPoseValid', 'fusionPose')
if raw is not None:
raw['roll'] = raw.pop('x')
raw['pitch'] = raw.pop('y')
raw['yaw'] = raw.pop('z')
self._last_orientation = raw
return deepcopy(self._last_orientation) | def get_orientation_radians(self) | Returns a dictionary object to represent the current orientation in
radians using the aircraft principal axes of pitch, roll and yaw | 4.697909 | 4.407848 | 1.065806 |
orientation = self.get_orientation_radians()
for key, val in orientation.items():
deg = math.degrees(val) # Result is -180 to +180
orientation[key] = deg + 360 if deg < 0 else deg
return orientation | def get_orientation_degrees(self) | Returns a dictionary object to represent the current orientation
in degrees, 0 to 360, using the aircraft principal axes of
pitch, roll and yaw | 4.034705 | 3.522526 | 1.145401 |
self.set_imu_config(True, False, False)
orientation = self.get_orientation_degrees()
if type(orientation) is dict and 'yaw' in orientation.keys():
return orientation['yaw']
else:
return None | def get_compass(self) | Gets the direction of North from the magnetometer in degrees | 4.802472 | 4.350265 | 1.103949 |
raw = self._get_raw_data('compassValid', 'compass')
if raw is not None:
self._last_compass_raw = raw
return deepcopy(self._last_compass_raw) | def get_compass_raw(self) | Magnetometer x y z raw data in uT (micro teslas) | 5.716808 | 5.113862 | 1.117904 |
raw = self._get_raw_data('gyroValid', 'gyro')
if raw is not None:
self._last_gyro_raw = raw
return deepcopy(self._last_gyro_raw) | def get_gyroscope_raw(self) | Gyroscope x y z raw data in radians per second | 5.512565 | 5.4006 | 1.020732 |
raw = self._get_raw_data('accelValid', 'accel')
if raw is not None:
self._last_accel_raw = raw
return deepcopy(self._last_accel_raw) | def get_accelerometer_raw(self) | Accelerometer x y z raw data in Gs | 5.475734 | 5.382893 | 1.017247 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.