code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def get_physical_descriptor(self):
raw_data_type = c_ubyte * 1024
raw_data = raw_data_type()
if hid_dll.HidD_GetPhysicalDescriptor(self.hid_handle,
byref(raw_data), 1024 ):
return [x for x in raw_data]
return [] | Returns physical HID device descriptor | null | null | null | |
def send_output_report(self, data):
assert( self.is_opened() )
#make sure we have c_ubyte array storage
if not ( isinstance(data, ctypes.Array) and \
issubclass(data._type_, c_ubyte) ):
raw_data_type = c_ubyte * len(data)
raw_data = raw_dat... | Send input/output/feature report ID = report_id, data should be a
c_ubyte object with included the required report data | null | null | null | |
def send_feature_report(self, data):
assert( self.is_opened() )
#make sure we have c_ubyte array storage
if not ( isinstance(data, ctypes.Array) and issubclass(data._type_,
c_ubyte) ):
raw_data_type = c_ubyte * len(data)
raw_data = raw_data... | Send input/output/feature report ID = report_id, data should be a
c_byte object with included the required report data | null | null | null | |
def __reset_vars(self):
self.__button_caps_storage = list()
self.usages_storage = dict()
self.report_set = dict()
self.ptr_preparsed_data = None
self.hid_handle = None
#don't clean up the report queue because the
#consumer & producer threads mig... | Reset vars (for init or gc) | null | null | null | |
def close(self):
# free parsed data
if not self.is_opened():
return
self.__open_status = False
# abort all running threads first
if self.__reading_thread and self.__reading_thread.is_alive():
self.__reading_thread.abort()
#avo... | Release system resources | null | null | null | |
def __find_reports(self, report_type, usage_page, usage_id = 0):
"Find input report referencing HID usage control/data item"
if not self.is_opened():
raise HIDError("Device must be opened")
#
results = list()
if usage_page:
for report_id in self.rep... | Find input report referencing HID usage control/data item | null | null | null | |
def find_any_reports(self, usage_page = 0, usage_id = 0):
items = [
(HidP_Input, self.find_input_reports(usage_page, usage_id)),
(HidP_Output, self.find_output_reports(usage_page, usage_id)),
(HidP_Feature, self.find_feature_reports(usage_page, usage_id)),... | Find any report type referencing HID usage control/data item.
Results are returned in a dictionary mapping report_type to usage
lists. | null | null | null | |
def _process_raw_report(self, raw_report):
"Default raw input report data handler"
if not self.is_opened():
return
if not self.__evt_handlers and not self.__raw_handler:
return
if not raw_report[0] and \
(raw_report[0] not in self.__input... | Default raw input report data handler | null | null | null | |
def find_input_usage(self, full_usage_id):
for report_id, report_obj in self.__input_report_templates.items():
if full_usage_id in report_obj:
return report_id
return None | Check if full usage Id included in input reports set
Parameters:
full_usage_id Full target usage, use get_full_usage_id
Returns:
Report ID as integer value, or None if report does not exist with
target usage. Nottice that report ID 0 is a valid report. | null | null | null | |
def add_event_handler(self, full_usage_id, handler_function,
event_kind = HID_EVT_ALL, aux_data = None):
report_id = self.find_input_usage(full_usage_id)
if report_id != None:
# allow first zero to trigger changes and releases events
self.__input_report... | Add event handler for usage value/button changes,
returns True if the handler function was updated | null | null | null | |
def set_value(self, value):
if self.__is_value_array:
if len(value) == self.__report_count:
for index, item in enumerate(value):
self.__setitem__(index, item)
else:
raise ValueError("Value size should match report item s... | Set usage value within report | null | null | null | |
def get_value(self):
if self.__is_value_array:
if self.__bit_size == 8: #matching c_ubyte
return list(self.__value)
else:
result = []
for i in range(self.__report_count):
result.append(self.__getitem__(i... | Retreive usage value within report | null | null | null | |
def get_usage_string(self):
if self.string_index:
usage_string_type = c_wchar * MAX_HID_STRING_LENGTH
# 128 max string length
abuffer = usage_string_type()
hid_dll.HidD_GetIndexedString(
self.hid_report.get_hid_object().hid_handle,
... | Returns usage representation string (as embedded in HID device
if available) | null | null | null | |
def get_usages(self):
"Return a dictionary mapping full usages Ids to plain values"
result = dict()
for key, usage in self.items():
result[key] = usage.value
return result | Return a dictionary mapping full usages Ids to plain values | null | null | null | |
def __alloc_raw_data(self, initial_values=None):
#allocate c_ubyte storage
if self.__raw_data == None: #first time only, create storage
raw_data_type = c_ubyte * self.__raw_report_size
self.__raw_data = raw_data_type()
elif initial_values == self.__raw_data... | Pre-allocate re-usagle memory | null | null | null | |
def set_raw_data(self, raw_data):
#pre-parsed data should exist
assert(self.__hid_object.is_opened())
#valid length
if len(raw_data) != self.__raw_report_size:
raise HIDError( "Report size has to be %d elements (bytes)" \
% self.__raw_report_si... | Set usage values based on given raw data, item[0] is report_id,
length should match 'raw_data_length' value, best performance if
raw_data is c_ubyte ctypes array object type | null | null | null | |
def __prepare_raw_data(self):
"Format internal __raw_data storage according to usages setting"
#pre-parsed data should exist
if not self.__hid_object.ptr_preparsed_data:
raise HIDError("HID object close or unable to request pre parsed "\
"report data")
... | Format internal __raw_data storage according to usages setting | null | null | null | |
def get_raw_data(self):
if self.__report_kind != HidP_Output \
and self.__report_kind != HidP_Feature:
raise HIDError("Only for output or feature reports")
self.__prepare_raw_data()
#return read-only object for internal storage
return helpers.R... | Get raw HID report based on internal report item settings,
creates new c_ubytes storage | null | null | null | |
def send(self, raw_data = None):
if self.__report_kind != HidP_Output \
and self.__report_kind != HidP_Feature:
raise HIDError("Only for output or feature reports")
#valid length
if raw_data and (len(raw_data) != self.__raw_report_size):
ra... | Prepare HID raw report (unless raw_data is provided) and send
it to HID device | null | null | null | |
def get(self, do_process_raw_report = True):
"Read report from device"
assert(self.__hid_object.is_opened())
if self.__report_kind != HidP_Input and \
self.__report_kind != HidP_Feature:
raise HIDError("Only for input or feature reports")
# pre-alloc raw... | Read report from device | null | null | null | |
def inspect(self):
results = {}
for fname in dir(self):
if not fname.startswith('_'):
value = getattr(self, fname)
if isinstance(value, collections.Callable):
continue
results[fname] = value
return ... | Retreive dictionary of 'Field: Value' attributes | null | null | null | |
"Browse for mute usages and set value"
all_mutes = ( \
(0x8, 0x9), # LED page
(0x1, 0xA7), # desktop page
(0xb, 0x2f),
)
all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes]
# usually you'll find and open the target device, here we'll browse... | def set_mute(mute_value) | Browse for mute usages and set value | 6.330062 | 5.938952 | 1.065855 |
def on_hid_pnp(self, hid_event = None):
# keep old reference for UI updates
old_device = self.device
if hid_event:
print("Hey, a hid device just %s!" % hid_event)
if hid_event == "connected":
# test if our device is available
if se... | This function will be called on per class event changes, so we need
to test if our device has being connected or is just gone | null | null | null | |
def simple_decorator(decorator):
def new_decorator(funct_target):
decorated = decorator(funct_target)
decorated.__name__ = funct_target.__name__
decorated.__doc__ = funct_target.__doc__
decorated.__dict__.update(funct_target.__dict__)
return decorated
... | This decorator can be used to turn simple functions
into well-behaved decorators, so long as the decorators
are fairly simple. If a decorator expects a function and
returns a function (no descriptors), and if it doesn't
modify function attributes or docstring, then it is
eligible to use this. S... | null | null | null | |
def logging_decorator(func):
def you_will_never_see_this_name(*args, **kwargs):
print('calling %s ...' % func.__name__)
result = func(*args, **kwargs)
print('completed: %s' % func.__name__)
return result
return you_will_never_see_this_name | Allow logging function calls | null | null | null | |
def synchronized(lock):
@simple_decorator
def wrap(function_target):
def new_function(*args, **kw):
lock.acquire()
try:
return function_target(*args, **kw)
finally:
lock.release()
return ne... | Synchronization decorator.
Allos to set a mutex on any function | null | null | null | |
old_device = self.hid_device
if hid_event:
self.pnpChanged.emit(hid_event)
if hid_event == "connected":
# test if our device is available
if self.hid_device:
# see, at this point we could detect multiple devices!
# bu... | def on_hid_pnp(self, hid_event = None) | This function will be called on per class event changes, so we need
to test if our device has being connected or is just gone | 4.914111 | 4.667535 | 1.052828 |
def _on_hid_pnp(self, w_param, l_param):
"Process WM_DEVICECHANGE system messages"
new_status = "unknown"
if w_param == DBT_DEVICEARRIVAL:
# hid device attached
notify_obj = None
if int(l_param):
# Disable this error since pylint doesn't... | Process WM_DEVICECHANGE system messages | null | null | null | |
def _register_hid_notification(self):
# create structure, self initialized
notify_obj = DevBroadcastDevInterface()
h_notify = RegisterDeviceNotification(self.__hid_hwnd,
ctypes.byref(notify_obj), DEVICE_NOTIFY_WINDOW_HANDLE)
#
return int(h_notify) | Register HID notification events on any window (passed by window
handler), returns a notification handler | null | null | null | |
def _unregister_hid_notification(self):
"Remove PnP notification handler"
if not int(self.__h_notify):
return #invalid
result = UnregisterDeviceNotification(self.__h_notify)
self.__h_notify = None
return int(result) | Remove PnP notification handler | null | null | null | |
def write_documentation(self, output_file):
"Issue documentation report on output_file file like object"
if not self.is_opened():
raise helpers.HIDError("Device has to be opened to get documentation")
#format
class CompundVarDict(object):
def __init__(self, parent):
... | Issue documentation report on output_file file like object | null | null | null | |
def hook_wnd_proc(self):
self.__local_wnd_proc_wrapped = WndProcType(self.local_wnd_proc)
self.__old_wnd_proc = SetWindowLong(self.__local_win_handle,
GWL_WNDPROC,
self.__local_wnd_proc_wrapped) | Attach to OS Window message handler | null | null | null | |
def unhook_wnd_proc(self):
if not self.__local_wnd_proc_wrapped:
return
SetWindowLong(self.__local_win_handle,
GWL_WNDPROC,
self.__old_wnd_proc)
## Allow the ctypes wrapper to be garbage collected
self.__local... | Restore previous Window message handler | null | null | null | |
def local_wnd_proc(self, h_wnd, msg, w_param, l_param):
# performance note: has_key is the fastest way to check for a key when
# the key is unlikely to be found (which is the case here, since most
# messages will not have handlers). This is called via a ctypes shim
# for e... | Call the handler if one exists. | null | null | null | |
def read_values(target_usage):
# browse all devices
all_devices = hid.HidDeviceFilter().get_devices()
if not all_devices:
print("Can't find any non system HID device connected")
else:
# search for our target usage
usage_found = False
for device in all_devi... | read feature report values | null | null | null | |
"Browse for mute usages and set value"
all_mutes = ( \
(0x8, 0x9), # LED page
(0x1, 0xA7), # desktop page
(0xb, 0x2f),
)
all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes]
# usually you'll find and open the target device, here we'll browse... | def set_mute(mute_value) | Browse for mute usages and set value | 8.163596 | 7.476341 | 1.091924 |
def winapi_result( result ):
if not result:
raise WinApiException("%d (%x): %s" % (ctypes.GetLastError(),
ctypes.GetLastError(), ctypes.FormatError()))
return result | Validate WINAPI BOOL result, raise exception if failed | null | null | null | |
def enum_device_interfaces(h_info, guid):
dev_interface_data = SP_DEVICE_INTERFACE_DATA()
dev_interface_data.cb_size = sizeof(dev_interface_data)
device_index = 0
while SetupDiEnumDeviceInterfaces(h_info,
None,
byref(guid),
device_index,
by... | Function generator that returns a device_interface_data enumerator
for the given device interface info and GUID parameters | null | null | null | |
def get_device_path(h_info, interface_data, ptr_info_data = None):
required_size = c_ulong(0)
dev_inter_detail_data = SP_DEVICE_INTERFACE_DETAIL_DATA()
dev_inter_detail_data.cb_size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA)
# get actual storage requirement
SetupDiGetDeviceInte... | Returns Hardware device path
Parameters:
h_info, interface set info handler
interface_data, device interface enumeration data
ptr_info_data, pointer to SP_DEVINFO_DATA() instance to receive details | null | null | null | |
def open(self):
self.h_info = SetupDiGetClassDevs(byref(self.guid), None, None,
(DIGCF.PRESENT | DIGCF.DEVICEINTERFACE) )
return self.h_info | Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACEDEVICE
in the Flags parameter ... | null | null | null | |
def close(self):
if self.h_info and self.h_info != INVALID_HANDLE_VALUE:
# clean up
SetupDiDestroyDeviceInfoList(self.h_info)
self.h_info = None | Destroy allocated storage | null | null | null | |
def click_signal(target_usage, target_vendor_id):
# usually you'll find and open the target device, here we'll browse for the
# current connected devices
all_devices = hid.HidDeviceFilter(vendor_id = target_vendor_id).get_devices()
if not all_devices:
print("Can't find target device... | This function will find a particular target_usage over output reports on
target_vendor_id related devices, then it will flip the signal to simulate
a 'click' event | null | null | null | |
url = urlparse(ZONEINFO_URL)
log.info('Connecting to %s' % url.netloc)
ftp = ftplib.FTP(url.netloc)
ftp.login()
gzfile = BytesIO()
log.info('Fetching zoneinfo database')
ftp.retrbinary('RETR ' + url.path, gzfile.write)
gzfile.seek(0)
log.info('Extracting backwards data')
... | def update_old_names() | Fetches the list of old tz names and returns a mapping | 3.145263 | 2.971556 | 1.058456 |
if string:
if not isinstance(string, str):
string = str(string, 'utf-8', 'replace')
return unicodedata.normalize('NFKD', string).encode(
'ASCII', 'ignore').decode('ASCII')
return '' | def _normalize_str(self, string) | Remove special characters and strip spaces | 2.782294 | 2.507176 | 1.109732 |
def wrapper(cls):
def view_wrapper(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def inner(self, request, *args, **kwargs):
# get object
obj = get_object_from_classbased_instance(
self, queryset, reques... | def permission_required(perm, queryset=None,
login_url=None, raise_exception=False) | Permission check decorator for classbased generic view
This decorator works as class decorator
DO NOT use ``method_decorator`` or whatever while this decorator will use
``self`` argument for method of classbased generic view.
Parameters
----------
perm : string
A permission string
... | 2.323675 | 2.478449 | 0.937552 |
from django.views.generic.edit import BaseCreateView
# initialize request, args, kwargs of classbased_instance
# most of methods of classbased view assumed these attributes
# but these attributes is initialized in ``dispatch`` method.
instance.request = request
instance.args = args
inst... | def get_object_from_classbased_instance(
instance, queryset, request, *args, **kwargs) | Get object from an instance of classbased generic view
Parameters
----------
instance : instance
An instance of classbased generic view
queryset : instance
A queryset instance
request : instance
A instance of HttpRequest
Returns
-------
instance
An insta... | 3.781254 | 3.951503 | 0.956915 |
if not is_authenticated(user_obj):
return False
# construct the permission full name
add_permission = self.get_full_permission_string('add')
change_permission = self.get_full_permission_string('change')
delete_permission = self.get_full_permission_string('del... | def has_perm(self, user_obj, perm, obj=None) | Check if user have permission (of object)
If the user_obj is not authenticated, it return ``False``.
If no object is specified, it return ``True`` when the corresponding
permission was specified to ``True`` (changed from v0.7.0).
This behavior is based on the django system.
htt... | 2.158216 | 1.99607 | 1.081233 |
def wrapper(view_method):
@wraps(view_method, assigned=available_attrs(view_method))
def inner(self, request=None, *args, **kwargs):
if isinstance(self, HttpRequest):
from permission.decorators.functionbase import \
permission_required as deco... | def permission_required(perm, queryset=None,
login_url=None, raise_exception=False) | Permission check decorator for classbased/functionbased generic view
This decorator works as method or function decorator
DO NOT use ``method_decorator`` or whatever while this decorator will use
``self`` argument for method of classbased generic view.
Parameters
----------
perm : string
... | 2.941901 | 3.007507 | 0.978186 |
if hasattr(obj, 'iterator'):
return (field_lookup(x, field_path) for x in obj.iterator())
elif isinstance(obj, Iterable):
return (field_lookup(x, field_path) for x in iter(obj))
# split the path
field_path = field_path.split('__', 1)
if len(field_path) == 1:
return getat... | def field_lookup(obj, field_path) | Lookup django model field in similar way of django query lookup.
Args:
obj (instance): Django Model instance
field_path (str): '__' separated field path
Example:
>>> from django.db import model
>>> from django.contrib.auth.models import User
>>> class Article(models.Mod... | 2.256671 | 2.638365 | 0.855329 |
def wrapper(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def inner(request, *args, **kwargs):
_kwargs = copy.copy(kwargs)
# overwrite queryset if specified
if queryset:
_kwargs['queryset'] = queryset
# get ob... | def permission_required(perm, queryset=None,
login_url=None, raise_exception=False) | Permission check decorator for function-base generic view
This decorator works as function decorator
Parameters
----------
perm : string
A permission string
queryset : queryset or model
A queryset or model for finding object.
With classbased generic view, ``None`` for using... | 2.824472 | 3.032976 | 0.931254 |
queryset = kwargs['queryset']
object_id = kwargs.get('object_id', None)
slug = kwargs.get('slug', None)
slug_field = kwargs.get('slug_field', 'slug')
if object_id:
obj = get_object_or_404(queryset, pk=object_id)
elif slug and slug_field:
obj = get_object_or_404(queryset, **{... | def get_object_from_list_detail_view(request, *args, **kwargs) | Get object from generic list_detail.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None | 1.805133 | 2.083118 | 0.866553 |
from django.utils import timezone
datetime_now = timezone.now
except ImportError:
datetime_now = datetime.datetime.now
year, month, day = kwargs['year'], kwargs['month'], kwargs['day']
month_format = kwargs.get('month_format', '%b')
day_format = kwargs.get('day_format', '%d')
... | def get_object_from_date_based_view(request, *args, **kwargs): # noqa
import time
import datetime
from django.http import Http404
from django.db.models.fields import DateTimeField
try | Get object from generic date_based.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None | 2.083309 | 2.219486 | 0.938645 |
from permission.handlers import PermissionHandler
if model._meta.abstract:
raise ImproperlyConfigured(
'The model %s is abstract, so it cannot be registered '
'with permission.' % model)
if model in self._registry:
raise Ke... | def register(self, model, handler=None) | Register a permission handler to the model
Parameters
----------
model : django model class
A django model class
handler : permission handler class, string, or None
A permission handler class or a dotted path
Raises
------
ImproperlyConfi... | 3.243739 | 2.901804 | 1.117835 |
if model not in self._registry:
raise KeyError("A permission handler class have not been "
"registered for '%s' yet" % model)
# remove from registry
del self._registry[model] | def unregister(self, model) | Unregister a permission handler from the model
Parameters
----------
model : django model class
A django model class
Raises
------
KeyError
Raise when the model have not registered in registry yet. | 6.601956 | 5.245935 | 1.25849 |
if not hasattr(self, '_app_perms_cache'):
self._app_perms_cache = get_app_perms(self.app_label)
return self._app_perms_cache | def _get_app_perms(self, *args) | Get permissions related to the application specified in constructor
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings | 2.327166 | 2.715129 | 0.857111 |
if not hasattr(self, '_model_perms_cache'):
if self.model is None:
self._model_perms_cache = set()
else:
self._model_perms_cache = get_model_perms(self.model)
return self._model_perms_cache | def _get_model_perms(self, *args) | Get permissions related to the model specified in constructor
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings | 2.102553 | 2.28318 | 0.920888 |
if not hasattr(self, '_perms_cache'):
if (self.includes and
isinstance(self.includes, collections.Callable)):
includes = self.includes(self)
else:
includes = self.includes or []
if (self.excludes and
... | def get_supported_permissions(self) | Get permissions which this handler can treat.
Specified with :attr:`includes` and :attr:`excludes` of this instance.
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings | 2.173221 | 2.050086 | 1.060064 |
get_app_label = lambda x: x.split(".", 1)[0]
if not hasattr(self, '_app_labels_cache'):
perms = self.get_supported_permissions()
self._app_labels_cache = set([get_app_label(x) for x in perms])
return self._app_labels_cache | def get_supported_app_labels(self) | Get app labels which this handler can treat.
Specified with :attr:`includes` and :attr:`excludes` of this instance.
Returns
-------
set
A set instance of app_label | 2.833823 | 3.343412 | 0.847584 |
cache_name = "_has_module_perms_%s_%s_cache" % (app_label, user_obj.pk)
if hasattr(self, cache_name):
return getattr(self, cache_name)
if self.app_label != app_label:
setattr(self, cache_name, False)
else:
for permission in self.get_supported_... | def has_module_perms(self, user_obj, app_label) | Check if user have permission of specified app
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
app_label : string
Django application name
Returns
-------
boolean
Whethe... | 2.11421 | 2.375789 | 0.889898 |
if perm not in self.get_supported_permissions():
return False
# use cache to reduce method call
CACHE_NAME = '_logical_perms_cache'
if not hasattr(user_obj, CACHE_NAME):
setattr(user_obj, CACHE_NAME, {})
cache = getattr(user_obj, CACHE_NAME)
... | def has_perm(self, user_obj, perm, obj=None) | Check if user have permission (of object) based on
specified models's ``_permission_logics`` attribute.
The result will be stored in user_obj as a cache to reduce method call.
Parameters
----------
user_obj : django user model instance
A django user model instance w... | 2.722896 | 2.691277 | 1.011749 |
# convert model to queryset
if queryset_or_model and issubclass(queryset_or_model, Model):
queryset_or_model = queryset_or_model._default_manager.all()
def wrapper(class_or_method):
if inspect.isclass(class_or_method):
from permission.decorators.classbase import \
... | def permission_required(perm, queryset_or_model=None,
login_url=None, raise_exception=False) | Permission check decorator for classbased/functional generic view
This decorator works as class, method or function decorator without any
modification.
DO NOT use ``method_decorator`` or whatever while this decorator will use
``self`` argument for method of classbased generic view.
Parameters
... | 3.266176 | 3.997052 | 0.817146 |
try:
perm = perm.split('.', 1)[1]
except IndexError as e:
if not fail_silently:
raise e
return perm | def get_perm_codename(perm, fail_silently=True) | Get permission codename from permission-string.
Examples
--------
>>> get_perm_codename('app_label.codename_model')
'codename_model'
>>> get_perm_codename('app_label.codename')
'codename'
>>> get_perm_codename('codename_model')
'codename_model'
>>> get_perm_codename('codename')
... | 2.89027 | 4.100763 | 0.704813 |
app_label = permission.content_type.app_label
codename = permission.codename
return '%s.%s' % (app_label, codename) | def permission_to_perm(permission) | Convert a permission instance to a permission-string.
Examples
--------
>>> permission = Permission.objects.get(
... content_type__app_label='auth',
... codename='add_user',
... )
>>> permission_to_perm(permission)
'auth.add_user' | 2.326917 | 3.232644 | 0.719819 |
from django.contrib.auth.models import Permission
try:
app_label, codename = perm.split('.', 1)
except (ValueError, IndexError):
raise AttributeError(
'The format of identifier string permission (perm) is wrong. '
"It should be in 'app_label.codename'."
)... | def perm_to_permission(perm) | Convert a permission-string to a permission instance.
Examples
--------
>>> permission = perm_to_permission('auth.add_user')
>>> permission.content_type.app_label
'auth'
>>> permission.codename
'add_user' | 3.102898 | 3.372295 | 0.920115 |
from django.contrib.auth.models import Permission
if isinstance(model_or_app_label, string_types):
app_label = model_or_app_label
else:
# assume model_or_app_label is model class
app_label = model_or_app_label._meta.app_label
qs = Permission.objects.filter(content_type__app_... | def get_app_perms(model_or_app_label) | Get permission-string list of the specified django application.
Parameters
----------
model_or_app_label : model class or string
A model class or app_label string to specify the particular django
application.
Returns
-------
set
A set of perms of the specified django ap... | 1.877386 | 2.145027 | 0.875228 |
from django.contrib.auth.models import Permission
app_label = model._meta.app_label
model_name = model._meta.object_name.lower()
qs = Permission.objects.filter(content_type__app_label=app_label,
content_type__model=model_name)
perms = ('%s.%s' % (app_label, p.... | def get_model_perms(model) | Get permission-string list of a specified django model.
Parameters
----------
model : model class
A model class to specify the particular django model.
Returns
-------
set
A set of perms of the specified django model.
Examples
--------
>>> sorted(get_model_perms(Pe... | 1.870899 | 2.286828 | 0.81812 |
if not is_authenticated(user_obj):
return False
# construct the permission full name
change_permission = self.get_full_permission_string('change')
delete_permission = self.get_full_permission_string('delete')
if obj is None:
# object permission wi... | def has_perm(self, user_obj, perm, obj=None) | Check if user have permission (of object)
If the user_obj is not authenticated, it return ``False``.
If no object is specified, it return ``True`` when the corresponding
permission was specified to ``True`` (changed from v0.7.0).
This behavior is based on the django system.
htt... | 3.186633 | 2.648153 | 1.203342 |
if not isinstance(permission_logic, PermissionLogic):
raise AttributeError(
'`permission_logic` must be an instance of PermissionLogic')
if not hasattr(model, '_permission_logics'):
model._permission_logics = set()
if not hasattr(model, '_permission_handler'):
from permi... | def add_permission_logic(model, permission_logic) | Add permission logic to the model
Parameters
----------
model : django model class
A django model class which will be treated by the specified permission
logic
permission_logic : permission logic instance
A permission logic instance which will be used to determine permission
... | 3.639498 | 3.751273 | 0.970204 |
if not hasattr(model, '_permission_logics'):
model._permission_logics = set()
if not isinstance(permission_logic, PermissionLogic):
# remove all permission logic of related
remove_set = set()
for _permission_logic in model._permission_logics:
if _permission_logic... | def remove_permission_logic(model, permission_logic, fail_silently=True) | Remove permission logic to the model
Parameters
----------
model : django model class
A django model class which will be treated by the specified permission
logic
permission_logic : permission logic class or instance
A permission logic class or instance which will be used to det... | 2.455661 | 2.66445 | 0.921639 |
from django.utils.module_loading import module_has_submodule
from permission.compat import import_module
from permission.conf import settings
module_name = module_name or settings.PERMISSION_AUTODISCOVER_MODULE_NAME
app_names = (app.name for app in apps.app_configs.values())
for app in ap... | def autodiscover(module_name=None) | Autodiscover INSTALLED_APPS perms.py modules and fail silently when not
present. This forces an import on them to register any permissions bits
they may want. | 3.300138 | 3.323119 | 0.993085 |
from permission.compat import import_module
from permission.compat import get_model
from permission.conf import settings
from permission.utils.logics import add_permission_logic
variable_name = settings.PERMISSION_AUTODISCOVER_VARIABLE_NAME
module_name = module_name or settings.PERMISSION_... | def discover(app, module_name=None) | Automatically apply the permission logics written in the specified
module.
Examples
--------
Assume if you have a ``perms.py`` in ``your_app`` as::
from permission.logics import AuthorPermissionLogic
PERMISSION_LOGICS = (
('your_app.your_model', AuthorPermissionLogic),
... | 3.259814 | 2.873824 | 1.134312 |
if not is_authenticated(user_obj):
return False
# construct the permission full name
change_permission = self.get_full_permission_string('change')
delete_permission = self.get_full_permission_string('delete')
# check if the user is authenticated
if ob... | def has_perm(self, user_obj, perm, obj=None) | Check if user have permission of himself
If the user_obj is not authenticated, it return ``False``.
If no object is specified, it return ``True`` when the corresponding
permission was specified to ``True`` (changed from v0.7.0).
This behavior is based on the django system.
http... | 3.426648 | 2.91938 | 1.173759 |
if not getattr(self, 'model', None):
raise AttributeError("You need to use `add_permission_logic` to "
"register the instance to the model class "
"before calling this method.")
app_label = self.model._meta.app_label
... | def get_full_permission_string(self, perm) | Return full permission string (app_label.perm_model) | 3.29236 | 3.195675 | 1.030255 |
path = request.build_absolute_uri()
# if the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = \
urlparse(login_url or settings.LOGIN_URL)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_... | def redirect_to_login(request, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME) | redirect to login | 1.601451 | 1.583219 | 1.011516 |
if settings.PERMISSION_CHECK_PERMISSION_PRESENCE:
# get permission instance from string permission (perm)
# it raise ObjectDoesNotExists when the permission is not exists
try:
perm_to_permission(perm)
except AttributeError:
... | def has_perm(self, user_obj, perm, obj=None) | Check if user have permission (of object) based on registered handlers.
It will raise ``ObjectDoesNotExist`` exception when the specified
string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
Parameters
-------... | 5.727621 | 4.707671 | 1.216657 |
# get permission handlers fot this perm
cache_name = '_%s_cache' % app_label
if hasattr(self, cache_name):
handlers = getattr(self, cache_name)
else:
handlers = [h for h in registry.get_handlers()
if app_label in h.get_supported_ap... | def has_module_perms(self, user_obj, app_label) | Check if user have permission of specified app based on registered
handlers.
It will raise ``ObjectDoesNotExist`` exception when the specified
string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
Parameters
... | 2.886615 | 3.208604 | 0.899648 |
return x.eval(context), y.eval(context) | def of_operator(context, x, y) | 'of' operator of permission if
This operator is used to specify the target object of permission | 8.136063 | 16.891453 | 0.481667 |
user = x.eval(context)
perm = y.eval(context)
if isinstance(perm, (list, tuple)):
perm, obj = perm
else:
obj = None
return user.has_perm(perm, obj) | def has_operator(context, x, y) | 'has' operator of permission if
This operator is used to specify the user object of permission | 4.477583 | 3.208058 | 1.39573 |
bits = token.split_contents()
ELIF = "el%s" % bits[0]
ELSE = "else"
ENDIF = "end%s" % bits[0]
# {% if ... %}
bits = bits[1:]
condition = do_permissionif.Parser(parser, bits).parse()
nodelist = parser.parse((ELIF, ELSE, ENDIF))
conditions_nodelists = [(condition, nodelist)]
... | def do_permissionif(parser, token) | Permission if templatetag
Examples
--------
::
{% if user has 'blogs.add_article' %}
<p>This user have 'blogs.add_article' permission</p>
{% elif user has 'blog.change_article' of object %}
<p>This user have 'blogs.change_article' permission of {{object}}</p>
... | 2.28338 | 2.362081 | 0.966682 |
body = six.text_type('')
for part in message.walk():
if part.get('content-disposition', '').startswith('attachment;'):
continue
if part.get_content_maintype() == maintype and \
part.get_content_subtype() == subtype:
charset = part.get_content_charset(... | def get_body_from_message(message, maintype, subtype) | Fetchs the body message matching main/sub content type. | 2.703555 | 2.714181 | 0.996085 |
ut.check_range([AreaCircle, ">0", "AreaCircle"])
return np.sqrt(4 * AreaCircle / np.pi) | def diam_circle(AreaCircle) | Return the diameter of a circle. | 10.040789 | 10.316316 | 0.973292 |
ut.check_range([temp, ">0", "Temperature in Kelvin"])
rhointerpolated = interpolate.CubicSpline(WATER_DENSITY_TABLE[0],
WATER_DENSITY_TABLE[1])
return np.asscalar(rhointerpolated(temp)) | def density_water(temp) | Return the density of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin. | 7.366238 | 8.364954 | 0.880607 |
ut.check_range([temp, ">0", "Temperature in Kelvin"])
return (viscosity_dynamic(temp).magnitude
/ density_water(temp).magnitude) | def viscosity_kinematic(temp) | Return the kinematic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin. | 13.696004 | 15.217354 | 0.900025 |
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Diam, ">0", "Diameter"],
[Nu, ">0", "Nu"])
return (4 * FlowRate) / (np.pi * Diam * Nu) | def re_pipe(FlowRate, Diam, Nu) | Return the Reynolds Number for a pipe. | 5.24335 | 5.003956 | 1.047841 |
ut.check_range([Width, ">0", "Width"], [DistCenter, ">0", "DistCenter"],
[openchannel, "boolean", "openchannel"])
if openchannel:
return (Width*DistCenter) / (Width + 2*DistCenter)
# if openchannel is True, the channel is open. Otherwise, the channel
# is assumed ... | def radius_hydraulic(Width, DistCenter, openchannel) | Return the hydraulic radius.
Width and DistCenter are length values and openchannel is a boolean. | 4.504116 | 4.577384 | 0.983993 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([FlowRate, ">0", "Flow rate"], [Nu, ">0", "Nu"])
return (4 * FlowRate
* radius_hydraulic(Width, DistCenter, openchannel).magnitude
/ (Width * DistCenter * Nu)) | def re_rect(FlowRate, Width, DistCenter, Nu, openchannel) | Return the Reynolds Number for a rectangular channel. | 14.934783 | 14.762019 | 1.011703 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Vel, ">=0", "Velocity"], [Nu, ">0", "Nu"])
return 4 * radius_hydraulic_general(Area, PerimWetted).magnitude * Vel / Nu | def re_general(Vel, Area, PerimWetted, Nu) | Return the Reynolds Number for a general cross section. | 17.767473 | 16.444458 | 1.080454 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([PipeRough, "0-1", "Pipe roughness"])
if re_pipe(FlowRate, Diam, Nu) >= RE_TRANSITION_PIPE:
#Swamee-Jain friction factor for turbulent flow; best for
#Re>3000 and ε/Diam ... | def fric(FlowRate, Diam, Nu, PipeRough) | Return the friction factor for pipe flow.
This equation applies to both laminar and turbulent flows. | 10.148821 | 9.501453 | 1.068134 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([PipeRough, "0-1", "Pipe roughness"])
if re_rect(FlowRate,Width,DistCenter,Nu,openchannel) >= RE_TRANSITION_PIPE:
#Swamee-Jain friction factor adapted for rectangular channel.
... | def fric_rect(FlowRate, Width, DistCenter, Nu, PipeRough, openchannel) | Return the friction factor for a rectangular channel. | 10.20603 | 9.603209 | 1.062773 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([PipeRough, "0-1", "Pipe roughness"])
if re_general(Vel, Area, PerimWetted, Nu) >= RE_TRANSITION_PIPE:
#Swamee-Jain friction factor adapted for any cross-section.
#Diam =... | def fric_general(Area, PerimWetted, Vel, Nu, PipeRough) | Return the friction factor for a general channel. | 10.148748 | 9.743149 | 1.041629 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Length, ">0", "Length"])
return (fric(FlowRate, Diam, Nu, PipeRough)
* 8 / (gravity.magnitude * np.pi**2)
* (Length * FlowRate**2) / Diam**5
) | def headloss_fric(FlowRate, Diam, Length, Nu, PipeRough) | Return the major head loss (due to wall shear) in a pipe.
This equation applies to both laminar and turbulent flows. | 15.509681 | 16.357176 | 0.948188 |
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Diam, ">0", "Diameter"],
[KMinor, ">=0", "K minor"])
return KMinor * 8 / (gravity.magnitude * np.pi**2) * FlowRate**2 / Diam**4 | def headloss_exp(FlowRate, Diam, KMinor) | Return the minor head loss (due to expansions) in a pipe.
This equation applies to both laminar and turbulent flows. | 7.622972 | 8.155015 | 0.934759 |
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
return (headloss_fric(FlowRate, Diam, Length, Nu, PipeRough).magnitude
+ headloss_exp(FlowRate, Diam, KMinor).magnitude) | def headloss(FlowRate, Diam, Length, Nu, PipeRough, KMinor) | Return the total head loss from major and minor losses in a pipe.
This equation applies to both laminar and turbulent flows. | 7.417667 | 7.698458 | 0.963526 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Length, ">0", "Length"])
return (fric_rect(FlowRate, Width, DistCenter, Nu,
PipeRough, openchannel)
* Length
/ (4 * radius_hydraulic(Width,... | def headloss_fric_rect(FlowRate, Width, DistCenter, Length, Nu, PipeRough, openchannel) | Return the major head loss due to wall shear in a rectangular channel.
This equation applies to both laminar and turbulent flows. | 11.690243 | 12.200131 | 0.958206 |
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"],
[DistCenter, ">0", "DistCenter"], [KMinor, ">=0", "K minor"])
return (KMinor * FlowRate**2
/ (2 * gravity.magnitude * (Width*DistCenter)**2)
) | def headloss_exp_rect(FlowRate, Width, DistCenter, KMinor) | Return the minor head loss due to expansion in a rectangular channel.
This equation applies to both laminar and turbulent flows. | 6.886482 | 7.171885 | 0.960205 |
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
return (headloss_exp_rect(FlowRate, Width, DistCenter, KMinor).magnitude
+ headloss_fric_rect(FlowRate, Width, DistCenter, Length,
Nu, PipeRough, openchann... | def headloss_rect(FlowRate, Width, DistCenter, Length,
KMinor, Nu, PipeRough, openchannel) | Return the total head loss in a rectangular channel.
Total head loss is a combination of the major and minor losses.
This equation applies to both laminar and turbulent flows. | 6.013257 | 6.755669 | 0.890105 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Length, ">0", "Length"])
return (fric_general(Area, PerimWetted, Vel, Nu, PipeRough) * Length
/ (4 * radius_hydraulic_general(Area, PerimWetted).magnitude)
* Vel... | def headloss_fric_general(Area, PerimWetted, Vel, Length, Nu, PipeRough) | Return the major head loss due to wall shear in the general case.
This equation applies to both laminar and turbulent flows. | 11.268723 | 11.965631 | 0.941757 |
#Checking input validity
ut.check_range([Vel, ">0", "Velocity"], [KMinor, '>=0', 'K minor'])
return KMinor * Vel**2 / (2*gravity.magnitude) | def headloss_exp_general(Vel, KMinor) | Return the minor head loss due to expansion in the general case.
This equation applies to both laminar and turbulent flows. | 14.346955 | 16.045399 | 0.894148 |
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
return (headloss_exp_general(Vel, KMinor).magnitude
+ headloss_fric_general(Area, PerimWetted, Vel,
Length, Nu, PipeRough).magnitude) | def headloss_gen(Area, Vel, PerimWetted, Length, KMinor, Nu, PipeRough) | Return the total head lossin the general case.
Total head loss is a combination of major and minor losses.
This equation applies to both laminar and turbulent flows. | 8.247746 | 8.337748 | 0.989205 |
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([NumOutlets, ">0, int", 'Number of outlets'])
return (headloss(FlowRate, Diam, Length, Nu, PipeRough, KMinor).magnitude
* ((1/3 )
+ (1 / (2*NumOutlets))
... | def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, PipeRough, NumOutlets) | Return the total head loss through the manifold. | 10.922846 | 10.742167 | 1.01682 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.