_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q1400
ReportItem.set_value
train
def set_value(self, value): """Set usage value within report""" if self.__is_value_array: if len(value) == self.__report_count: for index, item in enumerate(value): self.__setitem__(index, item)
python
{ "resource": "" }
q1401
ReportItem.get_value
train
def get_value(self): """Retreive usage value within report""" if self.__is_value_array: if self.__bit_size == 8: #matching c_ubyte return list(self.__value) else: result = []
python
{ "resource": "" }
q1402
HidReport.get_usages
train
def get_usages(self): "Return a dictionary mapping full usages Ids to plain values" result = dict()
python
{ "resource": "" }
q1403
HidReport.__alloc_raw_data
train
def __alloc_raw_data(self, initial_values=None): """Pre-allocate re-usagle memory""" #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:
python
{ "resource": "" }
q1404
HidReport.get_raw_data
train
def get_raw_data(self): """Get raw HID report based on internal report item settings, creates new c_ubytes storage """ if self.__report_kind != HidP_Output \ and self.__report_kind != HidP_Feature: raise HIDError("Only for
python
{ "resource": "" }
q1405
HidReport.get
train
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
python
{ "resource": "" }
q1406
logging_decorator
train
def logging_decorator(func): """Allow logging function calls""" def you_will_never_see_this_name(*args, **kwargs): """Neither this docstring""" print('calling %s ...' % func.__name__)
python
{ "resource": "" }
q1407
synchronized
train
def synchronized(lock): """ Synchronization decorator. Allos to set a mutex on any function """ @simple_decorator def wrap(function_target): """Decorator wrapper""" def new_function(*args, **kw): """Decorated function with Mutex"""
python
{ "resource": "" }
q1408
HidPnPWindowMixin._on_hid_pnp
train
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
python
{ "resource": "" }
q1409
HidPnPWindowMixin._unregister_hid_notification
train
def _unregister_hid_notification(self): "Remove PnP notification handler" if not int(self.__h_notify):
python
{ "resource": "" }
q1410
WndProcHookMixin.hook_wnd_proc
train
def hook_wnd_proc(self): """Attach to OS Window message handler""" self.__local_wnd_proc_wrapped = WndProcType(self.local_wnd_proc)
python
{ "resource": "" }
q1411
WndProcHookMixin.unhook_wnd_proc
train
def unhook_wnd_proc(self): """Restore previous Window message handler""" if not self.__local_wnd_proc_wrapped: return SetWindowLong(self.__local_win_handle, GWL_WNDPROC,
python
{ "resource": "" }
q1412
WndProcHookMixin.local_wnd_proc
train
def local_wnd_proc(self, h_wnd, msg, w_param, l_param): """ Call the handler if one exists. """ # 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
python
{ "resource": "" }
q1413
read_values
train
def read_values(target_usage): """read feature report values""" # 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
python
{ "resource": "" }
q1414
winapi_result
train
def winapi_result( result ): """Validate WINAPI BOOL result, raise exception if failed""" if not result:
python
{ "resource": "" }
q1415
enum_device_interfaces
train
def enum_device_interfaces(h_info, guid): """Function generator that returns a device_interface_data enumerator for the given device interface info and GUID parameters """ dev_interface_data = SP_DEVICE_INTERFACE_DATA() dev_interface_data.cb_size = sizeof(dev_interface_data) device_index = 0 while SetupDiEnumDeviceInterfaces(h_info, None,
python
{ "resource": "" }
q1416
DeviceInterfaceSetInfo.open
train
def open(self): """ 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.
python
{ "resource": "" }
q1417
DeviceInterfaceSetInfo.close
train
def close(self): """Destroy allocated storage""" if self.h_info and self.h_info != INVALID_HANDLE_VALUE: # clean up
python
{ "resource": "" }
q1418
click_signal
train
def click_signal(target_usage, target_vendor_id): """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""" # 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!
python
{ "resource": "" }
q1419
update_old_names
train
def update_old_names(): """Fetches the list of old tz names and returns a mapping""" 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():
python
{ "resource": "" }
q1420
permission_required
train
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 """ def wrapper(cls): def view_wrapper(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def inner(self, request, *args, **kwargs):
python
{ "resource": "" }
q1421
get_object_from_classbased_instance
train
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 """ 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:
python
{ "resource": "" }
q1422
field_lookup
train
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')
python
{ "resource": "" }
q1423
permission_required
train
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 """ 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
python
{ "resource": "" }
q1424
get_object_from_list_detail_view
train
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 """ 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:
python
{ "resource": "" }
q1425
get_object_from_date_based_view
train
def get_object_from_date_based_view(request, *args, **kwargs): # noqa """ Get object from generic date_based.detail view Parameters ---------- request : instance An instance of HttpRequest Returns ------- instance An instance of model object or None """ import time import datetime from django.http import Http404 from django.db.models.fields import DateTimeField try: 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 = {
python
{ "resource": "" }
q1426
PermissionHandlerRegistry.register
train
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. """ 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:
python
{ "resource": "" }
q1427
PermissionHandlerRegistry.unregister
train
def unregister(self, model): """ Unregister a permission handler from the model Parameters ---------- model : django model class A django model class Raises ------
python
{ "resource": "" }
q1428
PermissionHandler._get_app_perms
train
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 """
python
{ "resource": "" }
q1429
PermissionHandler._get_model_perms
train
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 """ if not hasattr(self, '_model_perms_cache'):
python
{ "resource": "" }
q1430
PermissionHandler.has_module_perms
train
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 """ 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:
python
{ "resource": "" }
q1431
get_perm_codename
train
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')
python
{ "resource": "" }
q1432
permission_to_perm
train
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',
python
{ "resource": "" }
q1433
perm_to_permission
train
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' """ from django.contrib.auth.models import Permission try: app_label, codename = perm.split('.', 1) except (ValueError, IndexError): raise
python
{ "resource": "" }
q1434
get_app_perms
train
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.
python
{ "resource": "" }
q1435
get_model_perms
train
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)) == [
python
{ "resource": "" }
q1436
add_permission_logic
train
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()) """ if not isinstance(permission_logic, PermissionLogic): raise AttributeError( '`permission_logic` must be an instance of PermissionLogic') if not hasattr(model, '_permission_logics'):
python
{ "resource": "" }
q1437
remove_permission_logic
train
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) """ if not hasattr(model, '_permission_logics'): model._permission_logics
python
{ "resource": "" }
q1438
autodiscover
train
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. """ 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
python
{ "resource": "" }
q1439
discover
train
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') """ from permission.compat import import_module
python
{ "resource": "" }
q1440
OneselfPermissionLogic.has_perm
train
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). """ if not is_authenticated(user_obj): return False # construct the permission full name change_permission = self.get_full_permission_string('change') delete_permission =
python
{ "resource": "" }
q1441
redirect_to_login
train
def redirect_to_login(request, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """redirect to login""" 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)
python
{ "resource": "" }
q1442
PermissionBackend.has_module_perms
train
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. """ # get permission
python
{ "resource": "" }
q1443
of_operator
train
def of_operator(context, x, y): """ 'of' operator of permission if This operator is used to specify the target
python
{ "resource": "" }
q1444
has_operator
train
def has_operator(context, x, y): """ 'has' operator of permission if This operator is used to specify the user object of permission """ user = x.eval(context) perm =
python
{ "resource": "" }
q1445
do_permissionif
train
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>
python
{ "resource": "" }
q1446
diam_circle
train
def diam_circle(AreaCircle): """Return the diameter of a circle."""
python
{ "resource": "" }
q1447
density_water
train
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. """ ut.check_range([temp, ">0", "Temperature in Kelvin"])
python
{ "resource": "" }
q1448
viscosity_kinematic
train
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.
python
{ "resource": "" }
q1449
re_pipe
train
def re_pipe(FlowRate, Diam, Nu): """Return the Reynolds Number for a pipe.""" #Checking input validity ut.check_range([FlowRate, ">0", "Flow rate"], [Diam,
python
{ "resource": "" }
q1450
radius_hydraulic
train
def radius_hydraulic(Width, DistCenter, openchannel): """Return the hydraulic radius. Width and DistCenter are length values and openchannel is a boolean. """ ut.check_range([Width, ">0", "Width"], [DistCenter, ">0", "DistCenter"], [openchannel, "boolean", "openchannel"]) if openchannel:
python
{ "resource": "" }
q1451
re_rect
train
def re_rect(FlowRate, Width, DistCenter, Nu, openchannel): """Return the Reynolds Number for a rectangular channel.""" #Checking input validity - inputs not checked here are checked by #functions this function calls. ut.check_range([FlowRate, ">0", "Flow
python
{ "resource": "" }
q1452
re_general
train
def re_general(Vel, Area, PerimWetted, Nu): """Return the Reynolds Number for a general cross section.""" #Checking input validity - inputs not checked here are checked by #functions this function calls.
python
{ "resource": "" }
q1453
fric
train
def fric(FlowRate, Diam, Nu, PipeRough): """Return the friction factor for pipe flow. This equation applies to both laminar and turbulent flows. """ #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
python
{ "resource": "" }
q1454
fric_rect
train
def fric_rect(FlowRate, Width, DistCenter, Nu, PipeRough, openchannel): """Return the friction factor for a rectangular channel.""" #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,
python
{ "resource": "" }
q1455
fric_general
train
def fric_general(Area, PerimWetted, Vel, Nu, PipeRough): """Return the friction factor for a general channel.""" #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.
python
{ "resource": "" }
q1456
headloss
train
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.
python
{ "resource": "" }
q1457
headloss_fric_rect
train
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. """ #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,
python
{ "resource": "" }
q1458
headloss_exp_rect
train
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. """ #Checking input validity ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"],
python
{ "resource": "" }
q1459
headloss_rect
train
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. """ #Inputs do not need to be checked here because they are checked by #functions this function
python
{ "resource": "" }
q1460
headloss_fric_general
train
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. """ #Checking input validity
python
{ "resource": "" }
q1461
headloss_exp_general
train
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. """ #Checking input validity
python
{ "resource": "" }
q1462
headloss_gen
train
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. """ #Inputs do not need to be checked here because they are checked by #functions this function calls.
python
{ "resource": "" }
q1463
headloss_manifold
train
def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, PipeRough, NumOutlets): """Return the total head loss through the manifold.""" #Checking input validity - inputs not checked here are checked by #functions this function calls. ut.check_range([NumOutlets, ">0, int", 'Number of outlets'])
python
{ "resource": "" }
q1464
flow_orifice
train
def flow_orifice(Diam, Height, RatioVCOrifice): """Return the flow rate of the orifice.""" #Checking input validity ut.check_range([Diam, ">0", "Diameter"], [RatioVCOrifice, "0-1", "VC orifice ratio"]) if Height > 0:
python
{ "resource": "" }
q1465
flow_orifice_vert
train
def flow_orifice_vert(Diam, Height, RatioVCOrifice): """Return the vertical flow rate of the orifice.""" #Checking input validity ut.check_range([RatioVCOrifice, "0-1", "VC orifice ratio"]) if Height > -Diam / 2: flow_vert = integrate.quad(lambda z: (Diam * np.sin(np.arccos(z/(Diam/2))) * np.sqrt(Height - z) ),
python
{ "resource": "" }
q1466
head_orifice
train
def head_orifice(Diam, RatioVCOrifice, FlowRate): """Return the head of the orifice.""" #Checking input validity ut.check_range([Diam, ">0", "Diameter"], [FlowRate, ">0", "Flow rate"], [RatioVCOrifice, "0-1", "VC orifice ratio"]) return ((FlowRate
python
{ "resource": "" }
q1467
area_orifice
train
def area_orifice(Height, RatioVCOrifice, FlowRate): """Return the area of the orifice.""" #Checking input validity ut.check_range([Height, ">0", "Height"], [FlowRate, ">0", "Flow rate"],
python
{ "resource": "" }
q1468
num_orifices
train
def num_orifices(FlowPlant, RatioVCOrifice, HeadLossOrifice, DiamOrifice): """Return the number of orifices.""" #Inputs do not need to be checked here because they are checked by #functions this function calls. return np.ceil(area_orifice(HeadLossOrifice,
python
{ "resource": "" }
q1469
flow_hagen
train
def flow_hagen(Diam, HeadLossFric, Length, Nu): """Return the flow rate for laminar flow with only major losses.""" #Checking input validity ut.check_range([Diam, ">0", "Diameter"], [Length, ">0", "Length"],
python
{ "resource": "" }
q1470
flow_swamee
train
def flow_swamee(Diam, HeadLossFric, Length, Nu, PipeRough): """Return the flow rate for turbulent flow with only major losses.""" #Checking input validity ut.check_range([Diam, ">0", "Diameter"], [Length, ">0", "Length"], [HeadLossFric, ">0", "Headloss due to friction"], [Nu, ">0", "Nu"], [PipeRough, "0-1", "Pipe roughness"]) logterm
python
{ "resource": "" }
q1471
flow_pipemajor
train
def flow_pipemajor(Diam, HeadLossFric, Length, Nu, PipeRough): """Return the flow rate with only major losses. This function applies to both laminar and turbulent flows. """ #Inputs do not need to be checked
python
{ "resource": "" }
q1472
flow_pipeminor
train
def flow_pipeminor(Diam, HeadLossExpans, KMinor): """Return the flow rate with only minor losses. This function applies to both laminar and turbulent flows. """ #Checking input validity - inputs not checked here are checked by #functions this function calls. ut.check_range([HeadLossExpans, ">=0", "Headloss due to expansion"],
python
{ "resource": "" }
q1473
flow_pipe
train
def flow_pipe(Diam, HeadLoss, Length, Nu, PipeRough, KMinor): """Return the the flow in a straight pipe. This function works for both major and minor losses and works whether the flow is laminar or turbulent. """ #Inputs do not need to be checked here because they are checked by #functions this function calls. if KMinor == 0: FlowRate = flow_pipemajor(Diam, HeadLoss, Length, Nu, PipeRough).magnitude else: FlowRatePrev = 0 err = 1.0 FlowRate = min(flow_pipemajor(Diam, HeadLoss, Length, Nu, PipeRough).magnitude, flow_pipeminor(Diam, HeadLoss, KMinor).magnitude ) while err > 0.01: FlowRatePrev = FlowRate HLFricNew = (HeadLoss * headloss_fric(FlowRate, Diam, Length,
python
{ "resource": "" }
q1474
diam_swamee
train
def diam_swamee(FlowRate, HeadLossFric, Length, Nu, PipeRough): """Return the inner diameter of a pipe. The Swamee Jain equation is dimensionally correct and returns the inner diameter of a pipe given the flow rate and the head loss due to shear on the pipe walls. The Swamee Jain equation does NOT take minor losses into account. This equation ONLY applies to turbulent flow. """ #Checking input validity ut.check_range([FlowRate, ">0", "Flow rate"], [Length, ">0", "Length"], [HeadLossFric, ">0", "Headloss due to friction"],
python
{ "resource": "" }
q1475
diam_pipemajor
train
def diam_pipemajor(FlowRate, HeadLossFric, Length, Nu, PipeRough): """Return the pipe IDiam that would result in given major losses. This function applies to both laminar and turbulent flow. """ #Inputs do not need to be checked here because they are checked by #functions this function calls.
python
{ "resource": "" }
q1476
diam_pipeminor
train
def diam_pipeminor(FlowRate, HeadLossExpans, KMinor): """Return the pipe ID that would result in the given minor losses. This function applies to both laminar and turbulent flow. """ #Checking input validity
python
{ "resource": "" }
q1477
diam_pipe
train
def diam_pipe(FlowRate, HeadLoss, Length, Nu, PipeRough, KMinor): """Return the pipe ID that would result in the given total head loss. This function applies to both laminar and turbulent flow and incorporates both minor and major losses. """ #Inputs do not need to be checked here because they are checked by #functions this function calls. if KMinor == 0: Diam = diam_pipemajor(FlowRate, HeadLoss, Length, Nu, PipeRough).magnitude else: Diam = max(diam_pipemajor(FlowRate, HeadLoss, Length, Nu, PipeRough).magnitude, diam_pipeminor(FlowRate, HeadLoss, KMinor).magnitude) err = 1.00
python
{ "resource": "" }
q1478
width_rect_weir
train
def width_rect_weir(FlowRate, Height): """Return the width of a rectangular weir.""" #Checking input validity ut.check_range([FlowRate, ">0", "Flow rate"], [Height, ">0", "Height"]) return ((3 / 2) * FlowRate
python
{ "resource": "" }
q1479
headloss_weir
train
def headloss_weir(FlowRate, Width): """Return the headloss of a weir.""" #Checking input validity ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"]) return (((3/2) * FlowRate
python
{ "resource": "" }
q1480
flow_rect_weir
train
def flow_rect_weir(Height, Width): """Return the flow of a rectangular weir.""" #Checking input validity ut.check_range([Height, ">0", "Height"], [Width, ">0", "Width"])
python
{ "resource": "" }
q1481
height_water_critical
train
def height_water_critical(FlowRate, Width): """Return the critical local water depth.""" #Checking input validity ut.check_range([FlowRate, ">0", "Flow
python
{ "resource": "" }
q1482
vel_horizontal
train
def vel_horizontal(HeightWaterCritical): """Return the horizontal velocity.""" #Checking input
python
{ "resource": "" }
q1483
headloss_kozeny
train
def headloss_kozeny(Length, Diam, Vel, Porosity, Nu): """Return the Carmen Kozeny Sand Bed head loss.""" #Checking input validity ut.check_range([Length, ">0", "Length"], [Diam, ">0", "Diam"], [Vel, ">0", "Velocity"], [Nu, ">0", "Nu"],
python
{ "resource": "" }
q1484
ID_colored_tube
train
def ID_colored_tube(color): """Look up the inner diameter of Ismatec 3-stop tubing given its color code. :param color: Color of the 3-stop tubing :type color: string :returns: Inner diameter of the 3-stop tubing (mm) :rtype: float :Examples: >>> from aguaclara.research.peristaltic_pump import ID_colored_tube >>> from aguaclara.core.units import unit_registry as u >>> ID_colored_tube("yellow-blue") <Quantity(1.52, 'millimeter')> >>> ID_colored_tube("orange-yellow") <Quantity(0.51, 'millimeter')> >>> ID_colored_tube("purple-white")
python
{ "resource": "" }
q1485
flow_rate
train
def flow_rate(vol_per_rev, rpm): """Return the flow rate from a pump given the volume of fluid pumped per revolution and the desired pump speed. :param vol_per_rev: Volume of fluid output per revolution (dependent on pump and tubing) :type vol_per_rev: float :param rpm: Desired pump speed in revolutions per minute :type rpm: float :return: Flow rate of the pump (mL/s) :rtype: float
python
{ "resource": "" }
q1486
k_value_orifice
train
def k_value_orifice(pipe_id, orifice_id, orifice_l, q, nu=con.WATER_NU): """Calculates the minor loss coefficient of an orifice plate in a pipe. Parameters: pipe_id: Entrance pipe's inner diameter from which fluid flows. orifice_id: Orifice's inner diameter. orifice_l: Orifice's length from start to end. q: Fluid's q rate. nu: Fluid's dynamic viscosity of the fluid. Default: room temperature water (1 * 10**-6 * m**2/s) Returns: k-value at the orifice. """ if orifice_id > pipe_id: raise ValueError('The orifice\'s inner diameter cannot be larger than'
python
{ "resource": "" }
q1487
_k_value_square_reduction
train
def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f): """Returns the minor loss coefficient for a square reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. re: Reynold's number. f: Darcy friction factor. """
python
{ "resource": "" }
q1488
_k_value_tapered_reduction
train
def _k_value_tapered_reduction(ent_pipe_id, exit_pipe_id, fitting_angle, re, f): """Returns the minor loss coefficient for a tapered reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. fitting_angle: Fitting angle between entrance and exit pipes. re: Reynold's number. f: Darcy friction factor. """ k_value_square_reduction = _k_value_square_reduction(ent_pipe_id, exit_pipe_id,
python
{ "resource": "" }
q1489
drain_OD
train
def drain_OD(q_plant, T, depth_end, SDR): """Return the nominal diameter of the entrance tank drain pipe. Depth at the end of the flocculator is used for headloss and length calculation inputs in the diam_pipe calculation. Parameters ---------- q_plant: float Plant flow rate T: float Design temperature depth_end: float The depth of water at the end of the flocculator SDR: float Standard dimension ratio Returns ------- float ? Examples --------
python
{ "resource": "" }
q1490
num_plates_ET
train
def num_plates_ET(q_plant, W_chan): """Return the number of plates in the entrance tank. This number minimizes the total length of the plate settler unit. Parameters ---------- q_plant: float Plant flow rate W_chan: float Width of channel Returns ------- float ? Examples -------- >>> from
python
{ "resource": "" }
q1491
L_plate_ET
train
def L_plate_ET(q_plant, W_chan): """Return the length of the plates in the entrance tank. Parameters ---------- q_plant: float Plant flow rate W_chan: float Width of channel Returns ------- float ? Examples --------
python
{ "resource": "" }
q1492
Gran
train
def Gran(data_file_path): """Extract the data from a ProCoDA Gran plot file. The file must be the original tab delimited file. :param data_file_path: The path to the file. If the file is in the working directory, then the file name is sufficient. :return: collection of * **V_titrant** (*float*) - Volume of titrant in mL * **ph_data** (*numpy.array*) - pH of the sample * **V_sample** (*float*) - Volume of the original sample that was titrated in mL * **Normality_titrant** (*float*) - Normality of the acid used to titrate the sample in mole/L * **V_equivalent** (*float*) - Volume of acid required to consume all of the ANC in mL * **ANC** (*float*) - Acid Neutralizing Capacity of the sample in mole/L """ df = pd.read_csv(data_file_path, delimiter='\t', header=5) V_t = np.array(pd.to_numeric(df.iloc[0:, 0]))*u.mL pH = np.array(pd.to_numeric(df.iloc[0:, 1])) df = pd.read_csv(data_file_path, delimiter='\t', header=-1,
python
{ "resource": "" }
q1493
E_CMFR_N
train
def E_CMFR_N(t, N): """Calculate a dimensionless measure of the output tracer concentration from a spike input to a series of completely mixed flow reactors. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :param N: The number of completely mixed flow reactors (CMFRS) in series. Must be greater than 1. :type N: int :return: Dimensionless measure
python
{ "resource": "" }
q1494
E_Advective_Dispersion
train
def E_Advective_Dispersion(t, Pe): """Calculate a dimensionless measure of the output tracer concentration from a spike input to reactor with advection and dispersion. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :param Pe: The ratio of advection to dispersion ((mean fluid velocity)/(Dispersion*flow path length)) :type Pe: float :return: dimensionless measure of the output tracer concentration (concentration * volume of reactor) / (mass of tracer)
python
{ "resource": "" }
q1495
set_sig_figs
train
def set_sig_figs(n=4): """Set the number of significant figures used to print Pint, Pandas, and NumPy quantities. Args: n (int): Number of significant figures to
python
{ "resource": "" }
q1496
remove_notes
train
def remove_notes(data): """Omit notes from a DataFrame object, where notes are identified as rows with non-numerical entries in the first column. :param data: DataFrame object to remove notes from
python
{ "resource": "" }
q1497
day_fraction
train
def day_fraction(time): """Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: ..
python
{ "resource": "" }
q1498
time_column_index
train
def time_column_index(time, time_column): """Return the index of lowest time in the column of times that is greater than or equal to the given time. :param time: the time to index from the column of time; a day fraction :type time: float :param time_column: a list of times (in day fractions), must be increasing and equally spaced :type time_column: float list
python
{ "resource": "" }
q1499
data_from_dates
train
def data_from_dates(path, dates): """Return list DataFrames representing the ProCoDA datalogs stored in the given path and recorded on the given dates. :param path: The path to the folder containing the ProCoDA data file(s) :type path: string :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :return: a list DataFrame objects representing the ProCoDA datalogs corresponding with the given dates :rtype:
python
{ "resource": "" }