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_data_type()
for index in range( len(data) ):
raw_data[index] = data[index]
else:
raw_data = data
#
# Adding a lock when writing (overlapped writes)
over_write = winapi.OVERLAPPED()
over_write.h_event = winapi.CreateEvent(None, 0, 0, None)
if over_write.h_event:
try:
overlapped_write = over_write
winapi.WriteFile(int(self.hid_handle), byref(raw_data), len(raw_data),
None, byref(overlapped_write)) #none overlapped
error = ctypes.GetLastError()
if error == winapi.ERROR_IO_PENDING:
# overlapped operation in progress
result = error
elif error == 1167:
raise HIDError("Error device disconnected before write")
else:
raise HIDError("Error %d when trying to write to HID "\
"device: %s"%(error, ctypes.FormatError(error)) )
result = winapi.WaitForSingleObject(overlapped_write.h_event, 10000 )
if result != winapi.WAIT_OBJECT_0:
# If the write times out make sure to
# cancel it, otherwise memory could
# get corrupted if the async write
# completes after this functions returns
winapi.CancelIo( int(self.hid_handle) )
raise HIDError("Write timed out")
finally:
# Make sure the event is closed so resources aren't leaked
winapi.CloseHandle(over_write.h_event)
else:
return winapi.WriteFile(int(self.hid_handle), byref(raw_data),
len(raw_data),
None, None) #none overlapped
return True | 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_type()
for index in range( len(data) ):
raw_data[index] = data[index]
else:
raw_data = data
return hid_dll.HidD_SetFeature(int(self.hid_handle), byref(raw_data),
len(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 might needed it
self.__evt_handlers = dict()
#other
self.__reading_thread = None
self.__input_processing_thread = None
self._input_report_queue = None | 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()
#avoid posting new reports
if self._input_report_queue:
self._input_report_queue.release_events()
if self.__input_processing_thread and \
self.__input_processing_thread.is_alive():
self.__input_processing_thread.abort()
#properly close API handlers and pointers
if self.ptr_preparsed_data:
ptr_preparsed_data = self.ptr_preparsed_data
self.ptr_preparsed_data = None
hid_dll.HidD_FreePreparsedData(ptr_preparsed_data)
# wait for the reading thread to complete before closing device handle
if self.__reading_thread:
self.__reading_thread.join()
if self.hid_handle:
winapi.CloseHandle(self.hid_handle)
# make sure report procesing thread is closed
if self.__input_processing_thread:
self.__input_processing_thread.join()
#reset vars (for GC)
button_caps_storage = self.__button_caps_storage
self.__reset_vars()
while button_caps_storage:
item = button_caps_storage.pop()
del item | 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.report_set.get( report_type, set() ):
#build report object, gathering usages matching report_id
report_obj = HidReport(self, report_type, report_id)
if get_full_usage_id(usage_page, usage_id) in report_obj:
results.append( report_obj )
else:
#all (any one)
for report_id in self.report_set.get(report_type, set()):
report_obj = HidReport(self, report_type, report_id)
results.append( report_obj )
return results | 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)),
]
return dict([(t, r) for t, r in items if r]) | 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_report_templates):
# windows sends an empty array when disconnecting
# but, this might have a collision with report_id = 0
if not hid_device_path_exists(self.device_path):
#windows XP sends empty report when disconnecting
self.__reading_thread.abort() #device disconnected
return
if self.__raw_handler:
#this might slow down data throughput, but at the expense of safety
self.__raw_handler(helpers.ReadOnlyList(raw_report))
return
# using pre-parsed report templates, by report id
report_template = self.__input_report_templates[raw_report[0]]
# old condition snapshot
old_values = report_template.get_usages()
# parse incoming data
report_template.set_raw_data(raw_report)
# and compare it
event_applies = self.evt_decision
evt_handlers = self.__evt_handlers
for key in report_template.keys():
if key not in evt_handlers:
continue
#check if event handler exist!
for event_kind, handlers in evt_handlers[key].items():
#key=event_kind, values=handler set
new_value = report_template[key].value
if not event_applies[event_kind](old_values[key], new_value):
continue
#decision applies, call handlers
for function_handler in handlers:
#check if the application wants some particular parameter
if handlers[function_handler]:
function_handler(new_value,
event_kind, handlers[function_handler])
else:
function_handler(new_value, event_kind) | 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_templates[report_id][full_usage_id].__value = None
if report_id == None or not handler_function:
# do not add handler
return False
assert(isinstance(handler_function, collections.Callable)) # must be a function
# get dictionary for full usages
top_map_handler = self.__evt_handlers.get(full_usage_id, dict())
event_handler_set = top_map_handler.get(event_kind, dict())
# update handler
event_handler_set[handler_function] = aux_data
if event_kind not in top_map_handler:
top_map_handler[event_kind] = event_handler_set
if full_usage_id not in self.__evt_handlers:
self.__evt_handlers[full_usage_id] = top_map_handler
return True | 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 size "\
"length" )
else:
self.__value = value & ((1 << self.__bit_size) - 1) | 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))
return result
else:
return self.__value | 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,
self.string_index,
byref(abuffer), MAX_HID_STRING_LENGTH-1 )
return abuffer.value
return "" | 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:
# already
return
else:
#initialize
ctypes.memset(self.__raw_data, 0, len(self.__raw_data))
if initial_values:
for index in range(len(initial_values)):
self.__raw_data[index] = initial_values[index] | 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_size )
# copy to internal storage
self.__alloc_raw_data(raw_data)
if not self.__usage_data_list: # create HIDP_DATA buffer
max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind,
self.__hid_object.ptr_preparsed_data)
data_list_type = winapi.HIDP_DATA * max_items
self.__usage_data_list = data_list_type()
#reference HIDP_DATA buffer
data_list = self.__usage_data_list
data_len = c_ulong(len(data_list))
#reset old values
for item in self.values():
if item.is_value_array():
item.value = [0, ]*len(item)
else:
item.value = 0
#ready, parse raw data
HidStatus( hid_dll.HidP_GetData(self.__report_kind,
byref(data_list), byref(data_len),
self.__hid_object.ptr_preparsed_data,
byref(self.__raw_data), len(self.__raw_data)) )
#set values on internal report item objects
for idx in range(data_len.value):
value_item = data_list[idx]
report_item = self.__idx_items.get(value_item.data_index)
if not report_item:
# This is not expected to happen
continue
if report_item.is_value():
report_item.value = value_item.value.raw_value
elif report_item.is_button():
report_item.value = value_item.value.on
else:
pass # HID API should give us either, at least one of 'em
#get values of array items
for item in self.__value_array_items:
#ask hid API to parse
HidStatus( hid_dll.HidP_GetUsageValueArray(self.__report_kind,
item.page_id,
0, #link collection
item.usage_id, #short usage
byref(item.value_array), #output data (c_ubyte storage)
len(item.value_array), self.__hid_object.ptr_preparsed_data,
byref(self.__raw_data), len(self.__raw_data)) ) | 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")
# make sure pre-memory allocation already done
self.__alloc_raw_data()
try:
HidStatus( hid_dll.HidP_InitializeReportForID(self.__report_kind,
self.__report_id, self.__hid_object.ptr_preparsed_data,
byref(self.__raw_data), self.__raw_report_size) )
#
except HIDError:
self.__raw_data[0] = self.__report_id
#check if we have pre-allocated usage storage
if not self.__usage_data_list: # create HIDP_DATA buffer
max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind,
self.__hid_object.ptr_preparsed_data)
if not max_items:
raise HIDError("Internal error while requesting usage length")
data_list_type = winapi.HIDP_DATA * max_items
self.__usage_data_list = data_list_type()
#reference HIDP_DATA buffer
data_list = self.__usage_data_list
#set buttons and values usages first
n_total_usages = 0
single_usage = USAGE()
single_usage_len = c_ulong()
for data_index, report_item in self.__idx_items.items():
if (not report_item.is_value_array()) and \
report_item.value != None:
#set by user, include in request
if report_item.is_button() and report_item.value:
# windows just can't handle button arrays!, we just don't
# know if usage is button array or plain single usage, so
# we set all usages at once
single_usage.value = report_item.usage_id
single_usage_len.value = 1
HidStatus( hid_dll.HidP_SetUsages(self.__report_kind,
report_item.page_id, 0,
byref(single_usage), byref(single_usage_len),
self.__hid_object.ptr_preparsed_data,
byref(self.__raw_data), self.__raw_report_size) )
continue
elif report_item.is_value() and \
not report_item.is_value_array():
data_list[n_total_usages].value.raw_value = report_item.value
else:
continue #do nothing
data_list[n_total_usages].reserved = 0 #reset
data_list[n_total_usages].data_index = data_index #reference
n_total_usages += 1
#set data if any usage is not 'none' (and not any value array)
if n_total_usages:
#some usages set
usage_len = c_ulong(n_total_usages)
HidStatus( hid_dll.HidP_SetData(self.__report_kind,
byref(data_list), byref(usage_len),
self.__hid_object.ptr_preparsed_data,
byref(self.__raw_data), self.__raw_report_size) )
#set values based on value arrays
for report_item in self.__value_array_items:
HidStatus( hid_dll.HidP_SetUsageValueArray(self.__report_kind,
report_item.page_id,
0, #all link collections
report_item.usage_id,
byref(report_item.value_array),
len(report_item.value_array),
self.__hid_object.ptr_preparsed_data, byref(self.__raw_data),
len(self.__raw_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.ReadOnlyList(self.__raw_data) | 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):
raise HIDError("Report size has to be %d elements (bytes)" \
% self.__raw_report_size)
#should be valid report id
if raw_data and raw_data[0] != self.__report_id.value:
#hint, raw_data should be a plain list of integer values
raise HIDError("Not matching report id")
#
if self.__report_kind != HidP_Output and \
self.__report_kind != HidP_Feature:
raise HIDError("Can only send output or feature reports")
#
if not raw_data:
# we'll construct the raw report
self.__prepare_raw_data()
elif not ( isinstance(raw_data, ctypes.Array) and \
issubclass(raw_data._type_, c_ubyte) ):
# pre-memory allocation for performance
self.__alloc_raw_data(raw_data)
#reference proper object
raw_data = self.__raw_data
if self.__report_kind == HidP_Output:
return self.__hid_object.send_output_report(raw_data)
elif self.__report_kind == HidP_Feature:
return self.__hid_object.send_feature_report(raw_data)
else:
pass | 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 data
self.__alloc_raw_data()
# now use it
raw_data = self.__raw_data
raw_data[0] = self.__report_id
read_function = None
if self.__report_kind == HidP_Feature:
read_function = hid_dll.HidD_GetFeature
elif self.__report_kind == HidP_Input:
read_function = hid_dll.HidD_GetInputReport
if read_function and read_function(int(self.__hid_object.hid_handle),
byref(raw_data), len(raw_data)):
#success
if do_process_raw_report:
self.set_raw_data(raw_data)
self.__hid_object._process_raw_report(raw_data)
return helpers.ReadOnlyList(raw_data)
return helpers.ReadOnlyList([]) | 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 results | 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 for the
# current connected devices
all_devices = hid.find_all_hid_devices()
success = 0
if not all_devices:
print("Can't any HID device!")
else:
# search for our target usage
# target pageId, usageId
for device in all_devices:
try:
device.open()
# target 'to set' value could be in feature or output reports
for report in device.find_output_reports() + device.find_feature_reports():
for target_usage in all_target_usages:
if target_usage in report:
# set our value and send
print("Found in report: {0}\n".format(report))
old_raw_data = report.get_raw_data()
print(" Empty raw report: {0}".format(old_raw_data))
report[target_usage] = value
new_raw_data = report.get_raw_data()
print(" Set raw report: {0}\n".format(new_raw_data))
# validate that set_raw_data() is working properly
report.set_raw_data( new_raw_data )
report.send()
success += 1
finally:
device.close()
# fit to sys.exit() proper result values
print("{0} Mute usage(s) set\n".format(success))
if success:
return 0
return -1 | 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 self.device:
# see, at this point we could detect multiple devices!
# but... we only want just one
pass
else:
self.test_for_connection()
elif hid_event == "disconnected":
# the hid object is automatically closed on disconnection we just
# test if still is plugged (important as the object might be
# closing)
if self.device and not self.device.is_plugged():
self.device = None
print("you removed my hid device!")
else:
# poll for devices
self.test_for_connection()
if old_device != self.device:
# update ui
pass | 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
# Now a few lines needed to make simple_decorator itself
# be a well-behaved decorator.
new_decorator.__name__ = decorator.__name__
new_decorator.__doc__ = decorator.__doc__
new_decorator.__dict__.update(decorator.__dict__)
return new_decorator | 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. Simply apply @simple_decorator to
your decorator and it will automatically preserve the
docstring and function attributes of functions to which
it is applied. | 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 new_function
return wrap | 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!
# but... we only want just one
pass
else:
self.test_for_connection()
elif hid_event == "disconnected":
# the hid object is automatically closed on disconnection we just
# test if still is plugged (important as the object might be
# closing)
if self.hid_device and not self.hid_device.is_plugged():
self.hid_device = None
else:
# poll for devices
self.test_for_connection()
# update ui
if old_device != self.hid_device:
if hid_event == "disconnected":
self.hidConnected.emit(old_device, hid_event)
else:
self.hidConnected.emit(self.hid_device, hid_event) | 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 reconize
# that from_address actually exists
# pylint: disable=no-member
notify_obj = DevBroadcastDevInterface.from_address(l_param)
#confirm if the right message received
if notify_obj and \
notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE:
#only connect if already disconnected
new_status = "connected"
elif w_param == DBT_DEVICEREMOVECOMPLETE:
# hid device removed
notify_obj = None
if int(l_param):
# Disable this error since pylint doesn't reconize
# that from_address actually exists
# pylint: disable=no-member
notify_obj = DevBroadcastDevInterface.from_address(l_param)
if notify_obj and \
notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE:
#only connect if already disconnected
new_status = "disconnected"
#verify if need to call event handler
if new_status != "unknown" and new_status != self.current_status:
self.current_status = new_status
self.on_hid_pnp(self.current_status)
#
return True | 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):
self.parent = parent
def __getitem__(self, key):
if '.' not in key:
return self.parent[key]
else:
all_keys = key.split('.')
curr_var = self.parent[all_keys[0]]
for item in all_keys[1:]:
new_var = getattr(curr_var, item)
curr_var = new_var
return new_var
dev_vars = vars(self)
dev_vars['main_usage_str'] = repr(
usage_pages.HidUsage(self.hid_caps.usage_page,
self.hid_caps.usage) )
output_file.write( % CompundVarDict(dev_vars)) #better than vars()!
#return
# inspect caps
for report_kind in [winapi.HidP_Input,
winapi.HidP_Output, winapi.HidP_Feature]:
all_usages = self.usages_storage.get(report_kind, [])
if all_usages:
output_file.write('*** %s Caps ***\n\n' % {
winapi.HidP_Input : "Input",
winapi.HidP_Output : "Output",
winapi.HidP_Feature : "Feature"
}[report_kind])
# normalize usages to allow sorting by usage or min range value
for item in all_usages:
if getattr(item, 'usage', None) != None:
item.flat_id = item.usage
elif getattr(item, 'usage_min', None) != None:
item.flat_id = item.usage_min
else:
item.flat_id = None
sorted(all_usages, key=attrgetter('usage_page', 'flat_id'))
for usage_item in all_usages:
# remove helper attribute
del usage_item.flat_id
all_items = usage_item.inspect()
# sort first by 'usage_page'...
usage_page = all_items["usage_page"]
del all_items["usage_page"]
if "usage" in all_items:
usage = all_items["usage"]
output_file.write(" Usage {0} ({0:#x}), "\
"Page {1:#x}\n".format(usage, usage_page))
output_file.write(" ({0})\n".format(
repr(usage_pages.HidUsage(usage_page, usage))) )
del all_items["usage"]
elif 'usage_min' in all_items:
usage = (all_items["usage_min"], all_items["usage_max"])
output_file.write(" Usage Range {0}~{1} ({0:#x}~{1:#x}),"
" Page {2:#x} ({3})\n".format(
usage[0], usage[1], usage_page,
str(usage_pages.UsagePage(usage_page))) )
del all_items["usage_min"]
del all_items["usage_max"]
else:
raise AttributeError("Expecting any usage id")
attribs = list( all_items.keys() )
attribs.sort()
for key in attribs:
if 'usage' in key:
output_file.write("{0}{1}: {2} ({2:#x})\n".format(' '*8,
key, all_items[key]))
else:
output_file.write("{0}{1}: {2}\n".format(' '*8,
key, all_items[key]))
output_file.write('\n') | 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_wnd_proc_wrapped = None | 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 every single windows message so dispatch speed is important
if msg in self.__msg_dict:
# if the handler returns false, we terminate the message here Note
# that we don't pass the hwnd or the message along Handlers should
# be really, really careful about returning false here
if self.__msg_dict[msg](w_param, l_param) == False:
return
# Restore the old WndProc on Destroy.
if msg == WM_DESTROY:
self.unhook_wnd_proc()
return CallWindowProc(self.__old_wnd_proc,
h_wnd, msg, w_param, l_param) | 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_devices:
try:
device.open()
# browse feature reports
for report in device.find_feature_reports():
if target_usage in report:
# we found our usage
report.get()
# print result
print("The value:", list(report[target_usage]))
print("All the report: {0}".format(report.get_raw_data()))
usage_found = True
finally:
device.close()
if not usage_found:
print("The target device was found, but the requested usage does not exist!\n") | 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 for the
# current connected devices
all_devices = hid.find_all_hid_devices()
success = 0
if not all_devices:
print("Can't any HID device!")
else:
# search for our target usage
# target pageId, usageId
for device in all_devices:
try:
device.open()
# target 'to set' value could be in feature or output reports
for report in device.find_output_reports() + device.find_feature_reports():
for target_usage in all_target_usages:
if target_usage in report:
# set our value and send
report[target_usage] = value
report.send()
success += 1
finally:
device.close()
# fit to sys.exit() proper result values
print("{0} Mute usage(s) set\n".format(success))
if success:
return 0
return -1 | 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,
byref(dev_interface_data) ):
yield dev_interface_data
device_index += 1
del dev_interface_data | 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
SetupDiGetDeviceInterfaceDetail(h_info, byref(interface_data),
None, 0, byref(required_size),
None)
ctypes.resize(dev_inter_detail_data, required_size.value)
# read value
SetupDiGetDeviceInterfaceDetail(h_info, byref(interface_data),
byref(dev_inter_detail_data), required_size, None,
ptr_info_data)
# extract string only
return dev_inter_detail_data.get_string() | 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 passed to SetupDiGetClassDevs. | 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 (vendor_id = 0x%04x)!" % target_vendor_id)
else:
# search for our target usage
# target pageId, usageId
for device in all_devices:
try:
device.open()
# browse output reports, we could search over feature reports also,
# changing find_output_reports() to find_feature_reports()
for report in device.find_output_reports():
if target_usage in report:
# found out target!
report[target_usage] = 1 # yes, changing values is that easy
# at this point you could change different usages at a time...
# and finally send the prepared output report
report.send()
# now toggle back the signal
report[target_usage] = 0
report.send()
print("\nUsage clicked!\n")
return
finally:
device.close()
print("The target device was found, but the requested usage does not exist!\n") | 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')
archive = tarfile.open(mode="r:gz", fileobj=gzfile)
backward = {}
for line in archive.extractfile('backward').readlines():
if line[0] == '#':
continue
if len(line.strip()) == 0:
continue
parts = line.split()
if parts[0] != b'Link':
continue
backward[parts[2].decode('ascii')] = parts[1].decode('ascii')
return backward | 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, request, *args, **kwargs
)
if not request.user.has_perm(perm, obj=obj):
if raise_exception:
raise PermissionDenied
else:
return redirect_to_login(request, login_url)
return view_func(self, request, *args, **kwargs)
return inner
cls.dispatch = view_wrapper(cls.dispatch)
return cls
return wrapper | 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
queryset : queryset or model
A queryset or model for finding object.
With classbased generic view, ``None`` for using view default queryset.
When the view does not define ``get_queryset``, ``queryset``,
``get_object``, or ``object`` then ``obj=None`` is used to check
permission.
With functional generic view, ``None`` for using passed queryset.
When non queryset was passed then ``obj=None`` is used to check
permission.
Examples
--------
>>> @permission_required('auth.change_user')
>>> class UpdateAuthUserView(UpdateView):
... pass | 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
instance.kwargs = kwargs
# get queryset from class if ``queryset_or_model`` is not specified
if hasattr(instance, 'get_queryset') and not queryset:
queryset = instance.get_queryset()
elif hasattr(instance, 'queryset') and not queryset:
queryset = instance.queryset
elif hasattr(instance, 'model') and not queryset:
queryset = instance.model._default_manager.all()
# get object
if hasattr(instance, 'get_object'):
try:
obj = instance.get_object(queryset)
except AttributeError as e:
# CreateView has ``get_object`` method but CreateView
# should not have any object before thus simply set
# None
if isinstance(instance, BaseCreateView):
obj = None
else:
raise e
elif hasattr(instance, 'object'):
obj = instance.object
else:
obj = None
return obj | 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 instance of model object or None | 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('delete')
if obj is None:
if user_obj.groups.filter(name__in=self.group_names):
if self.add_permission and perm == add_permission:
return True
if self.change_permission and perm == change_permission:
return True
if self.delete_permission and perm == delete_permission:
return True
return self.any_permission
return False
elif user_obj.is_active:
if user_obj.groups.filter(name__in=self.group_names):
if self.any_permission:
# have any kind of permissions to the obj
return True
if (self.add_permission and
perm == add_permission):
return True
if (self.change_permission and
perm == change_permission):
return True
if (self.delete_permission and
perm == delete_permission):
return True
return False | 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.
https://code.djangoproject.com/wiki/RowLevelPermissions
If an object is specified, it will return ``True`` if the user is
in group specified in ``group_names`` of this instance.
This permission logic is used mainly for group based role permission
system.
You can change this behavior to set ``any_permission``,
``add_permission``, ``change_permission``, or ``delete_permission``
attributes of this instance.
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object). | 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 decorator
# this is a functional view not classbased view.
decorator = decorator(perm, queryset,
login_url, raise_exception)
decorator = decorator(view_method)
if not request:
args = list(args)
args.insert(0, request)
request = self
return decorator(request, *args, **kwargs)
else:
from permission.decorators.classbase import \
get_object_from_classbased_instance
# get object
obj = get_object_from_classbased_instance(
self, queryset, request, *args, **kwargs
)
if not request.user.has_perm(perm, obj=obj):
if raise_exception:
raise PermissionDenied
else:
return redirect_to_login(request, login_url)
return view_method(self, request, *args, **kwargs)
return inner
return wrapper | 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
A permission string
queryset : queryset or model
A queryset or model for finding object.
With classbased generic view, ``None`` for using view default queryset.
When the view does not define ``get_queryset``, ``queryset``,
``get_object``, or ``object`` then ``obj=None`` is used to check
permission.
With functional generic view, ``None`` for using passed queryset.
When non queryset was passed then ``obj=None`` is used to check
permission.
Examples
--------
>>> # As method decorator
>>> class UpdateAuthUserView(UpdateView):
>>> @permission_required('auth.change_user')
>>> def dispatch(self, request, *args, **kwargs):
... pass
>>> # As function decorator
>>> @permission_required('auth.change_user')
>>> def update_auth_user(request, *args, **kwargs):
... pass | 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 getattr(obj, field_path[0], None)
return field_lookup(field_lookup(obj, field_path[0]), field_path[1]) | 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.Model):
>>> title = models.CharField('title', max_length=200)
>>> author = models.ForeignKey(User, null=True,
>>> related_name='permission_test_articles_author')
>>> editors = models.ManyToManyField(User,
>>> related_name='permission_test_articles_editors')
>>> user = User.objects.create_user('test_user', 'password')
>>> article = Article.objects.create(title='test_article',
... author=user)
>>> article.editors.add(user)
>>> assert 'test_article' == field_lookup(article, 'title')
>>> assert 'test_user' == field_lookup(article, 'user__username')
>>> assert ['test_user'] == list(field_lookup(article,
... 'editors__username')) | 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 object from view
if 'date_field' in _kwargs:
fn = get_object_from_date_based_view
else:
fn = get_object_from_list_detail_view
if fn.validate(request, *args, **_kwargs):
obj = fn(request, *args, **_kwargs)
else:
# required arguments is not passed
obj = None
if not request.user.has_perm(perm, obj=obj):
if raise_exception:
raise PermissionDenied
else:
return redirect_to_login(request, login_url)
return view_func(request, *args, **_kwargs)
return inner
return wrapper | 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 view default queryset.
When the view does not define ``get_queryset``, ``queryset``,
``get_object``, or ``object`` then ``obj=None`` is used to check
permission.
With functional generic view, ``None`` for using passed queryset.
When non queryset was passed then ``obj=None`` is used to check
permission.
Examples
--------
>>> @permission_required('auth.change_user')
>>> def update_auth_user(request, *args, **kwargs):
... pass | 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, **{slug_field: slug})
else:
raise AttributeError(
"Generic detail view must be called with either an "
"object_id or a slug/slug_field."
)
return obj | 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')
date_field = kwargs['date_field']
queryset = kwargs['queryset']
object_id = kwargs.get('object_id', None)
slug = kwargs.get('slug', None)
slug_field = kwargs.get('slug_field', 'slug')
try:
tt = time.strptime(
'%s-%s-%s' % (year, month, day),
'%s-%s-%s' % ('%Y', month_format, day_format)
)
date = datetime.date(*tt[:3])
except ValueError:
raise Http404
model = queryset.model
if isinstance(model._meta.get_field(date_field), DateTimeField):
lookup_kwargs = {
'%s__range' % date_field: (
datetime.datetime.combine(date, datetime.time.min),
datetime.datetime.combine(date, datetime.time.max),
)}
else:
lookup_kwargs = {date_field: date}
now = datetime_now()
if date >= now.date() and not kwargs.get('allow_future', False):
lookup_kwargs['%s__lte' % date_field] = now
if object_id:
lookup_kwargs['pk'] = object_id
elif slug and slug_field:
lookup_kwargs['%s__exact' % slug_field] = slug
else:
raise AttributeError(
"Generic detail view must be called with either an "
"object_id or a slug/slug_field."
)
return get_object_or_404(queryset, **lookup_kwargs) | 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 KeyError("A permission handler class is already "
"registered for '%s'" % model)
if handler is None:
handler = settings.PERMISSION_DEFAULT_PERMISSION_HANDLER
if isstr(handler):
handler = import_string(handler)
if not inspect.isclass(handler):
raise AttributeError(
"`handler` attribute must be a class. "
"An instance was specified.")
if not issubclass(handler, PermissionHandler):
raise AttributeError(
"`handler` attribute must be a subclass of "
"`permission.handlers.PermissionHandler`")
# Instantiate the handler to save in the registry
instance = handler(model)
self._registry[model] = instance | 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
------
ImproperlyConfigured
Raise when the model is abstract model
KeyError
Raise when the model is already registered in registry
The model cannot have more than one handler. | 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
isinstance(self.excludes, collections.Callable)):
excludes = self.excludes(self)
else:
excludes = self.excludes or []
includes = set(includes)
excludes = set(excludes)
includes = includes.difference(excludes)
self._perms_cache = includes
return self._perms_cache | 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_permissions():
if user_obj.has_perm(permission):
setattr(self, cache_name, True)
return True
setattr(self, cache_name, False)
return False | 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
Whether the specified user have any permissions of specified app | 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)
cachekey = "%s %s" % (perm, hash(obj))
if cachekey not in cache:
cache[cachekey] = self._has_perm(user_obj, perm, obj)
return cache[cachekey] | 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 which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object). | 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 \
permission_required as decorator
else:
# method_permission_required can handle method or function
# correctly.
from permission.decorators.methodbase import \
permission_required as decorator
return decorator(perm, queryset_or_model,
login_url, raise_exception)(class_or_method)
return wrapper | 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
----------
perm : string
A permission string
queryset_or_model : queryset or model
A queryset or model for finding object.
With classbased generic view, ``None`` for using view default queryset.
When the view does not define ``get_queryset``, ``queryset``,
``get_object``, or ``object`` then ``obj=None`` is used to check
permission.
With functional generic view, ``None`` for using passed queryset.
When non queryset was passed then ``obj=None`` is used to check
permission.
Examples
--------
>>> # As class decorator
>>> @permission_required('auth.change_user')
>>> class UpdateAuthUserView(UpdateView):
... pass
>>> # As method decorator
>>> class UpdateAuthUserView(UpdateView):
... @permission_required('auth.change_user')
... def dispatch(self, request, *args, **kwargs):
... pass
>>> # As function decorator
>>> @permission_required('auth.change_user')
>>> def update_auth_user(request, *args, **kwargs):
... pass
.. Note::
Classbased generic view is recommended while you can regulate the queryset
with ``get_queryset()`` method.
Detecting object from passed kwargs may not work correctly. | 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')
'codename'
>>> get_perm_codename('app_label.app_label.codename_model')
'app_label.codename_model' | 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'."
)
else:
permission = Permission.objects.get(
content_type__app_label=app_label,
codename=codename
)
return permission | 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_label=app_label)
perms = ('%s.%s' % (app_label, p.codename) for p in qs.iterator())
return set(perms) | 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 application.
Examples
--------
>>> perms1 = get_app_perms('auth')
>>> perms2 = get_app_perms(Permission)
>>> perms1 == perms2
True | 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.codename) for p in qs.iterator())
return set(perms) | 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(Permission)) == [
... 'auth.add_permission',
... 'auth.change_permission',
... 'auth.delete_permission'
... ]
True | 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 without obj should return True
# Ref: https://code.djangoproject.com/wiki/RowLevelPermissions
if self.any_permission:
return True
if self.change_permission and perm == change_permission:
return True
if self.delete_permission and perm == delete_permission:
return True
return False
elif user_obj.is_active:
# get collaborator queryset
collaborators = field_lookup(obj, self.field_name)
if hasattr(collaborators, 'all'):
collaborators = collaborators.all()
if user_obj in collaborators:
if self.any_permission:
# have any kind of permissions to the obj
return True
if (self.change_permission and
perm == change_permission):
return True
if (self.delete_permission and
perm == delete_permission):
return True
return False | 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.
https://code.djangoproject.com/wiki/RowLevelPermissions
If an object is specified, it will return ``True`` if the user is
found in ``field_name`` of the object (e.g. ``obj.collaborators``).
So once the object store the user as a collaborator in
``field_name`` attribute (default: ``collaborators``), the collaborator
can change or delete the object (you can change this behavior to set
``any_permission``, ``change_permission`` or ``delete_permission``
attributes of this instance).
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object). | 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 permission.utils.handlers import registry
# register default permission handler
registry.register(model, handler=None)
model._permission_logics.add(permission_logic)
# store target model to the permission_logic instance
permission_logic.model = model | 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
of the model
Examples
--------
>>> from django.db import models
>>> from permission.logics import PermissionLogic
>>> class Mock(models.Model):
... name = models.CharField('name', max_length=120)
>>> add_permission_logic(Mock, PermissionLogic()) | 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.__class__ == permission_logic:
remove_set.add(_permission_logic)
# difference
model._permission_logics = model._permission_logics.difference(remove_set)
else:
if fail_silently and permission_logic not in model._permission_logics:
pass
else:
model._permission_logics.remove(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 determine
permission of the model
fail_silently : boolean
If `True` then do not raise KeyError even the specified permission logic
have not registered.
Examples
--------
>>> from django.db import models
>>> from permission.logics import PermissionLogic
>>> class Mock(models.Model):
... name = models.CharField('name', max_length=120)
>>> logic = PermissionLogic()
>>> add_permission_logic(Mock, logic)
>>> remove_permission_logic(Mock, logic) | 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 app_names:
mod = import_module(app)
# Attempt to import the app's perms module
try:
# discover the permission module
discover(app, module_name=module_name)
except:
# Decide whether to bubble up this error. If the app just doesn't
# have an perms module, we can just ignore the error attempting
# to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, module_name):
raise | 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_AUTODISCOVER_MODULE_NAME
# import the module
m = import_module('%s.%s' % (app, module_name))
# check if the module have PERMISSION_LOGICS variable
if hasattr(m, variable_name):
# apply permission logics automatically
permission_logic_set = getattr(m, variable_name)
for model, permission_logic in permission_logic_set:
if isinstance(model, six.string_types):
# convert model string to model instance
model = get_model(*model.split('.', 1))
add_permission_logic(model, permission_logic) | 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),
)
Use this method to apply the permission logics enumerated in
``PERMISSION_LOGICS`` variable like:
>>> discover('your_app') | 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 obj is None:
# object permission without obj should return True
# Ref: https://code.djangoproject.com/wiki/RowLevelPermissions
if self.any_permission:
return True
if self.change_permission and perm == change_permission:
return True
if self.delete_permission and perm == delete_permission:
return True
return False
elif user_obj.is_active:
# check if the user trying to interact with himself
if obj == user_obj:
if self.any_permission:
# have any kind of permissions to himself
return True
if (self.change_permission and
perm == change_permission):
return True
if (self.delete_permission and
perm == delete_permission):
return True
return False | 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.
https://code.djangoproject.com/wiki/RowLevelPermissions
If an object is specified, it will return ``True`` if the object is the
user.
So users can change or delete themselves (you can change this behavior
to set ``any_permission``, ``change_permissino`` or
``delete_permission`` attributes of this instance).
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object). | 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
model_name = self.model._meta.object_name.lower()
return "%s.%s_%s" % (app_label, perm, model_name) | 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_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import \
redirect_to_login as auth_redirect_to_login
return auth_redirect_to_login(path, login_url, redirect_field_name) | 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:
# Django 1.2 internally use wrong permission string thus ignore
pass
# get permission handlers fot this perm
cache_name = '_%s_cache' % perm
if hasattr(self, cache_name):
handlers = getattr(self, cache_name)
else:
handlers = [h for h in registry.get_handlers()
if perm in h.get_supported_permissions()]
setattr(self, cache_name, handlers)
for handler in handlers:
if handler.has_perm(user_obj, perm, obj=obj):
return True
return False | 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
----------
user_obj : django user model instance
A django user model instance which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object).
Raises
------
django.core.exceptions.ObjectDoesNotExist
If the specified string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module. | 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_app_labels()]
setattr(self, cache_name, handlers)
for handler in handlers:
if handler.has_module_perms(user_obj, app_label):
return True
return False | 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
----------
user_obj : django user model instance
A django user model instance which is checked
app_label : string
`app_label.codename` formatted permission string
Returns
-------
boolean
Whether the specified user have specified permission.
Raises
------
django.core.exceptions.ObjectDoesNotExist
If the specified string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module. | 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)]
token = parser.next_token()
# {% elif ... %} (repeatable)
while token.contents.startswith(ELIF):
bits = token.split_contents()[1:]
condition = do_permissionif.Parser(parser, bits).parse()
nodelist = parser.parse((ELIF, ELSE, ENDIF))
conditions_nodelists.append((condition, nodelist))
token = parser.next_token()
# {% else %} (optional)
if token.contents == ELSE:
nodelist = parser.parse((ENDIF,))
conditions_nodelists.append((None, nodelist))
token = parser.next_token()
# {% endif %}
assert token.contents == ENDIF
return IfNode(conditions_nodelists) | 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>
{% endif %}
{# If you set 'PERMISSION_REPLACE_BUILTIN_IF = False' in settings #}
{% permission user has 'blogs.add_article' %}
<p>This user have 'blogs.add_article' permission</p>
{% elpermission user has 'blog.change_article' of object %}
<p>This user have 'blogs.change_article' permission of {{object}}</p>
{% endpermission %} | 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()
this_part = part.get_payload(decode=True)
if charset:
try:
this_part = this_part.decode(charset, 'replace')
except LookupError:
this_part = this_part.decode('ascii', 'replace')
logger.warning(
'Unknown encoding %s encountered while decoding '
'text payload. Interpreting as ASCII with '
'replacement, but some data may not be '
'represented as the sender intended.',
charset
)
except ValueError:
this_part = this_part.decode('ascii', 'replace')
logger.warning(
'Error encountered while decoding text '
'payload from an incorrectly-constructed '
'e-mail; payload was converted to ASCII with '
'replacement, but some data may not be '
'represented as the sender intended.'
)
else:
this_part = this_part.decode('ascii', 'replace')
body += this_part
return body | 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 to have a top.
else:
return (Width*DistCenter) / (2 * (Width+DistCenter)) | 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 < 0.02
f = (0.25 / (np.log10(PipeRough / (3.7 * Diam)
+ 5.74 / re_pipe(FlowRate, Diam, Nu) ** 0.9
)
) ** 2
)
else:
f = 64 / re_pipe(FlowRate, Diam, Nu)
return f | 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.
#Diam = 4*R_h in this case.
return (0.25
/ (np.log10((PipeRough
/ (3.7 * 4
* radius_hydraulic(Width, DistCenter,
openchannel).magnitude
)
)
+ (5.74 / (re_rect(FlowRate, Width, DistCenter,
Nu, openchannel) ** 0.9)
)
)
) ** 2
)
else:
return 64 / re_rect(FlowRate, Width, DistCenter, Nu, openchannel) | 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 = 4*R*h
f= (0.25 /
(np.log10((PipeRough
/ (3.7 * 4
* radius_hydraulic_general(Area, PerimWetted).magnitude
)
)
+ (5.74
/ re_general(Vel, Area, PerimWetted, Nu) ** 0.9
)
)
) ** 2
)
else:
f = 64 / re_general(Vel, Area, PerimWetted, Nu)
return f | 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, DistCenter, openchannel).magnitude)
* FlowRate**2
/ (2 * gravity.magnitude * (Width*DistCenter)**2)
) | 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, openchannel).magnitude) | 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**2 / (2*gravity.magnitude)
) | 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))
+ (1 / (6*NumOutlets**2))
)
) | 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.