Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def requires_user(fn): @functools.wraps(fn) def wrap(*args, **kwargs): subject = Yosai.get_current_subject() if subject.identifiers is None: msg = ("Attempting to perform a user-only operation. The " ...
[ "\n Requires that the calling Subject be *either* authenticated *or* remembered\n via RememberMe services before allowing access.\n\n This method essentially ensures that subject.identifiers IS NOT None\n\n :raises UnauthenticatedException: indicating that the decorated method is\n ...
Please provide a description of the function:def requires_permission(permission_s, logical_operator=all): def outer_wrap(fn): @functools.wraps(fn) def inner_wrap(*args, **kwargs): subject = Yosai.get_current_subject() subject.check_permission(per...
[ "\n Requires that the calling Subject be authorized to the extent that is\n required to satisfy the permission_s specified and the logical operation\n upon them.\n\n :param permission_s: the permission(s) required\n :type permission_s: a List of Strings or List of Permission in...
Please provide a description of the function:def requires_dynamic_permission(permission_s, logical_operator=all): def outer_wrap(fn): @functools.wraps(fn) def inner_wrap(*args, **kwargs): newperms = [perm.format(**kwargs) for perm in permission_s] ...
[ "\n This method requires that the calling Subject be authorized to the extent\n that is required to satisfy the dynamic permission_s specified and the logical\n operation upon them. Unlike ``requires_permission``, which uses statically\n defined permissions, this function derives a perm...
Please provide a description of the function:def requires_role(role_s, logical_operator=all): def outer_wrap(fn): @functools.wraps(fn) def inner_wrap(*args, **kwargs): subject = Yosai.get_current_subject() subject.check_role(role_s, logical_oper...
[ "\n Requires that the calling Subject be authorized to the extent that is\n required to satisfy the role_s specified and the logical operation\n upon them.\n\n :param role_s: a collection of the role(s) required, specified by\n identifiers (such as a role name...
Please provide a description of the function:def create_manager(self, yosai, settings, session_attributes): mgr_settings = SecurityManagerSettings(settings) attributes = mgr_settings.attributes realms = self._init_realms(settings, attributes['realms']) session_attributes = sel...
[ "\n Order of execution matters. The sac must be set before the cache_handler is\n instantiated so that the cache_handler's serialization manager instance\n registers the sac.\n " ]
Please provide a description of the function:def resolve_realms(self, attributes): realms = [] for realm, realm_attributes in attributes['realms'].items(): realm_cls = maybe_resolve(realm) account_store_cls = maybe_resolve(realm_attributes['account_store']) ...
[ "\n The format of realm settings is:\n {'name_of_realm':\n {'cls': 'location to realm class',\n 'account_store': 'location to realm account_store class'}}\n\n - 'name of realm' is a label used for internal tracking\n - 'cls' and 'account_store' ...
Please provide a description of the function:def init_realms(self, realms): # this eliminates the need for an authorizing_realms attribute: self.realms = tuple(realm for realm in realms if isinstance(realm, realm_abcs.AuthorizingRealm)) self.register_cache_cl...
[ "\n :type realms: tuple\n " ]
Please provide a description of the function:def _has_role(self, identifiers, role_s): for realm in self.realms: # the realm's has_role returns a generator yield from realm.has_role(identifiers, role_s)
[ "\n :type identifiers: subject_abcs.IdentifierCollection\n :type role_s: Set of String(s)\n " ]
Please provide a description of the function:def _is_permitted(self, identifiers, permission_s): for realm in self.realms: # the realm's is_permitted returns a generator yield from realm.is_permitted(identifiers, permission_s)
[ "\n :type identifiers: subject_abcs.IdentifierCollection\n\n :param permission_s: a collection of 1..N permissions\n :type permission_s: List of permission string(s)\n " ]
Please provide a description of the function:def is_permitted(self, identifiers, permission_s, log_results=True): self.assert_realms_configured() results = collections.defaultdict(bool) # defaults to False is_permitted_results = self._is_permitted(identifiers, permission_s) ...
[ "\n Yosai differs from Shiro in how it handles String-typed Permission\n parameters. Rather than supporting *args of String-typed Permissions,\n Yosai supports a list of Strings. Yosai remains true to Shiro's API\n while determining permissions a bit more pythonically. This may\n ...
Please provide a description of the function:def is_permitted_collective(self, identifiers, permission_s, logical_operator): self.assert_realms_configured() # interim_results is a set of tuples: interim_results = self.is_permitted(identifiers, permission...
[ "\n :param identifiers: a collection of Identifier objects\n :type identifiers: subject_abcs.IdentifierCollection\n\n :param permission_s: a collection of 1..N permissions\n :type permission_s: List of Permission object(s) or String(s)\n\n :param logical_operator: indicates whet...
Please provide a description of the function:def check_permission(self, identifiers, permission_s, logical_operator): self.assert_realms_configured() permitted = self.is_permitted_collective(identifiers, permission_s, ...
[ "\n like Yosai's authentication process, the authorization process will\n raise an Exception to halt further authz checking once Yosai determines\n that a Subject is unauthorized to receive the requested permission\n\n :param identifiers: a collection of identifiers\n :type identi...
Please provide a description of the function:def has_role(self, identifiers, role_s, log_results=True): self.assert_realms_configured() results = collections.defaultdict(bool) # defaults to False for role, has_role in self._has_role(identifiers, role_s): # checkrole expec...
[ "\n :param identifiers: a collection of identifiers\n :type identifiers: subject_abcs.IdentifierCollection\n\n :param role_s: a collection of 1..N Role identifiers\n :type role_s: Set of String(s)\n\n :param log_results: states whether to log results (True) or allow the\n ...
Please provide a description of the function:def has_role_collective(self, identifiers, role_s, logical_operator): self.assert_realms_configured() # interim_results is a set of tuples: interim_results = self.has_role(identifiers, role_s, log_results=False) results = logical_op...
[ "\n :param identifiers: a collection of identifiers\n :type identifiers: subject_abcs.IdentifierCollection\n\n :param role_s: a collection of 1..N Role identifiers\n :type role_s: Set of String(s)\n\n :param logical_operator: indicates whether all or at least one\n ...
Please provide a description of the function:def check_role(self, identifiers, role_s, logical_operator): self.assert_realms_configured() has_role_s = self.has_role_collective(identifiers, role_s, logical_operator) if not has_role_s: ...
[ "\n :param identifiers: a collection of identifiers\n :type identifiers: subject_abcs.IdentifierCollection\n\n :param role_s: 1..N role identifiers\n :type role_s: a String or Set of Strings\n\n :param logical_operator: indicates whether all or at least one\n ...
Please provide a description of the function:def add_collection(self, identifier_collection): try: new_source_identifiers = identifier_collection.source_identifiers self.source_identifiers.update(new_source_identifiers) except AttributeError: msg = "Invalid i...
[ "\n :type identifier_collection: a SimpleIdentifierCollection\n " ]
Please provide a description of the function:def by_type(self, identifier_class): myidentifiers = set() for identifier in self.source_identifiers.values(): if (isinstance(identifier, identifier_class)): myidentifiers.update([identifier]) return set(myidentifi...
[ "\n returns all unique instances of a type of identifier\n\n :param identifier_class: the class to match identifier with\n :returns: a tuple\n " ]
Please provide a description of the function:def create(self, session): sessionid = super().create(session) # calls _do_create and verify self._cache(session, sessionid) return sessionid
[ "\n caches the session and caches an entry to associate the cached session\n with the subject\n " ]
Please provide a description of the function:def is_timed_out(self): if (self.is_expired): return True try: if (not self.last_access_time): msg = ("session.last_access_time for session with id [" + str(self.session_id) + "] is null...
[ "\n determines whether a Session has been inactive/idle for too long a time\n OR exceeds the absolute time that a Session may exist\n ", "\n Calculate at what time a session would have been last accessed\n for it to be expired at this point. In other words, subtract\n...
Please provide a description of the function:def _retrieve_session(self, session_key): session_id = session_key.session_id if (session_id is None): msg = ("Unable to resolve session ID from SessionKey [{0}]." "Returning null to indicate a session could not be " ...
[ "\n :type session_key: SessionKey\n :returns: SimpleSession\n " ]
Please provide a description of the function:def do_get_session(self, session_key): session_id = session_key.session_id msg = ("do_get_session: Attempting to retrieve session with key " + str(session_id)) logger.debug(msg) session = self._retrieve_session(session...
[ "\n :type session_key: SessionKey\n :returns: SimpleSession\n " ]
Please provide a description of the function:def on_expiration(self, session, expired_session_exception=None, session_key=None): if (expired_session_exception and session_key): try: self.on_change(session) msg = "Session with id [{0}] ha...
[ "\n This method overloaded for now (java port). TBD\n Two possible scenarios supported:\n 1) All three arguments passed = session + ese + session_key\n 2) Only session passed as an argument\n " ]
Please provide a description of the function:def notify_event(self, session_info, topic): try: self.event_bus.sendMessage(topic, items=session_info) except AttributeError: msg = "Could not publish {} event".format(topic) raise AttributeError(msg)
[ "\n :type identifiers: SimpleIdentifierCollection\n " ]
Please provide a description of the function:def start(self, session_context): # is a SimpleSesson: session = self._create_session(session_context) self.session_handler.on_start(session, session_context) mysession = session_tuple(None, session.session_id) self.notify_e...
[ "\n unlike shiro, yosai does not apply session timeouts from within the\n start method of the SessionManager but rather defers timeout settings\n responsibilities to the SimpleSession, which uses session_settings\n " ]
Please provide a description of the function:def create_exposed_session(self, session, key=None, context=None): # shiro ignores key and context parameters return DelegatingSession(self, SessionKey(session.session_id))
[ "\n :type session: SimpleSession\n " ]
Please provide a description of the function:def get_session(self, key): # a SimpleSession: session = self.session_handler.do_get_session(key) if (session): return self.create_exposed_session(session, key) else: return None
[ "\n :returns: DelegatingSession\n " ]
Please provide a description of the function:def _lookup_required_session(self, key): session = self.session_handler.do_get_session(key) if (not session): msg = ("Unable to locate required Session instance based " "on session_key [" + str(key) + "].") ...
[ "\n :returns: SimpleSession\n " ]
Please provide a description of the function:def set_attributes(self, session_key, attributes): session = self._lookup_required_session(session_key) session.set_attributes(attributes) self.session_handler.on_change(session)
[ "\n :type attributes: dict\n " ]
Please provide a description of the function:def remove_attributes(self, session_key, attribute_keys): session = self._lookup_required_session(session_key) removed = session.remove_attributes(attribute_keys) if removed: self.session_handler.on_change(session) return ...
[ "\n :type attribute_keys: a list of strings\n " ]
Please provide a description of the function:def resolve_reference(ref): if not isinstance(ref, str) or ':' not in ref: return ref modulename, rest = ref.split(':', 1) try: obj = import_module(modulename) except ImportError as e: raise LookupError( 'error resolv...
[ "\n Return the object pointed to by ``ref``.\n If ``ref`` is not a string or does not contain ``:``, it is returned as is.\n References must be in the form <modulename>:<varname> where <modulename> is the fully\n qualified module name and varname is the path to the variable inside that module.\n For...
Please provide a description of the function:def qualified_name(obj): try: module = obj.__module__ qualname = obj.__qualname__ except AttributeError: type_ = type(obj) module = type_.__module__ qualname = type_.__qualname__ return qualname if module in ('typing'...
[ "Return the qualified name (e.g. package.module.Type) for the given object." ]
Please provide a description of the function:def add_item(session, item, quantity=1): shopping_cart = session.get_attribute('shopping_cart') if shopping_cart: shopping_cart.add_item(item, quantity) else: shopping_cart = ShoppingCart() shopping_cart.ad...
[ "\n :param item: a ShoppingCartItem namedtuple\n " ]
Please provide a description of the function:def first_realm_successful_strategy(authc_attempt): authc_token = authc_attempt.authentication_token realm_errors = [] account = None for realm in authc_attempt.realms: if (realm.supports(authc_token)): try: account = ...
[ "\n The FirstRealmSuccessfulStrategy will iterate over the available realms\n and invoke Realm.authenticate_account(authc_token) on each one. The moment\n that a realm returns an Account without raising an Exception, that account\n is returned immediately and all subsequent realms ignored entirely\n...
Please provide a description of the function:def _setup(self, name=None): envvar = self.__dict__['env_var'] if envvar: settings_file = os.environ.get(envvar) else: settings_file = self.__dict__['file_path'] if not settings_file: msg = ("Reque...
[ "\n Load the settings module referenced by env_var. This environment-\n defined configuration process is called during the settings\n configuration process.\n " ]
Please provide a description of the function:def _get_subject(self): web_registry = WebYosai.get_current_webregistry() subject_context = WebSubjectContext(yosai=self, security_manager=self.security_manager, ...
[ "\n Returns the currently accessible Subject available to the calling code\n depending on runtime environment.\n\n :param web_registry: The WebRegistry instance that knows how to interact\n with the web application's request and response APIs\n\n :returns: t...
Please provide a description of the function:def requires_authentication(fn): @functools.wraps(fn) def wrap(*args, **kwargs): subject = WebYosai.get_current_subject() if not subject.authenticated: msg = "The current Subject is not authenticated. ACCESS...
[ "\n Requires that the calling Subject be authenticated before allowing access.\n " ]
Please provide a description of the function:def requires_user(fn): @functools.wraps(fn) def wrap(*args, **kwargs): subject = WebYosai.get_current_subject() if subject.identifiers is None: msg = ("Attempting to perform a user-only operation. The " ...
[ "\n Requires that the calling Subject be *either* authenticated *or* remembered\n via RememberMe services before allowing access.\n\n This method essentially ensures that subject.identifiers IS NOT None\n " ]
Please provide a description of the function:def requires_permission(permission_s, logical_operator=all): def outer_wrap(fn): @functools.wraps(fn) def inner_wrap(*args, **kwargs): subject = WebYosai.get_current_subject() try: ...
[ "\n Requires that the calling Subject be authorized to the extent that is\n required to satisfy the permission_s specified and the logical operation\n upon them.\n\n :param permission_s: the permission(s) required\n :type permission_s: a List of Strings or List of Permission in...
Please provide a description of the function:def requires_dynamic_permission(permission_s, logical_operator=all): def outer_wrap(fn): @functools.wraps(fn) def inner_wrap(*args, **kwargs): params = WebYosai.get_current_webregistry().resource_params ...
[ "\n This method requires that the calling Subject be authorized to the extent\n that is required to satisfy the dynamic permission_s specified and the logical\n operation upon them. Unlike ``requires_permission``, which uses statically\n defined permissions, this function derives a perm...
Please provide a description of the function:def requires_role(role_s, logical_operator=all): def outer_wrap(fn): @functools.wraps(fn) def inner_wrap(*args, **kwargs): subject = WebYosai.get_current_subject() try: subject.che...
[ "\n Requires that the calling Subject be authorized to the extent that is\n required to satisfy the role_s specified and the logical operation\n upon them.\n\n :param role_s: a collection of the role(s) required, specified by\n identifiers (such as a role name...
Please provide a description of the function:def do_create_subject(self, subject_context): if not isinstance(subject_context, web_subject_abcs.WebSubjectContext): return super().do_create_subject(subject_context=subject_context) security_manager = subject_context.resolve_security_m...
[ "\n By the time this method is invoked, all possible\n ``SubjectContext`` data (session, identifiers, et. al.) has been made\n accessible using all known heuristics.\n\n :returns: a Subject instance reflecting the data in the specified\n SubjectContext data map\n ...
Please provide a description of the function:def remember_encrypted_identity(self, subject, encrypted): try: # base 64 encode it and store as a cookie: encoded = base64.b64encode(encrypted).decode('utf-8') subject.web_registry.remember_me = encoded except Att...
[ "\n Base64-encodes the specified serialized byte array and sets that\n base64-encoded String as the cookie value.\n\n The ``subject`` instance is expected to be a ``WebSubject`` instance\n with a web_registry handle so that an HTTP cookie may be set on an\n outgoing response. If ...
Please provide a description of the function:def get_remembered_encrypted_identity(self, subject_context): if (self.is_identity_removed(subject_context)): if not isinstance(subject_context, web_subject_abcs.WebSubjectContext): msg = ("SubjectContext argument is not an HTTP-a...
[ "\n Returns a previously serialized identity byte array or None if the byte\n array could not be acquired.\n\n This implementation retrieves an HTTP cookie, Base64-decodes the cookie\n value, and returns the resulting byte array.\n\n The ``subject_context`` instance is expected to...
Please provide a description of the function:def read_raw_temp(self): self._device.write8(BMP085_CONTROL, BMP085_READTEMPCMD) time.sleep(0.005) # Wait 5ms raw = self._device.readU16BE(BMP085_TEMPDATA) self._logger.debug('Raw temp 0x{0:X} ({1})'.format(raw & 0xFFFF, raw)) ...
[ "Reads the raw (uncompensated) temperature from the sensor." ]
Please provide a description of the function:def read_raw_pressure(self): self._device.write8(BMP085_CONTROL, BMP085_READPRESSURECMD + (self._mode << 6)) if self._mode == BMP085_ULTRALOWPOWER: time.sleep(0.005) elif self._mode == BMP085_HIGHRES: time.sleep(0.014)...
[ "Reads the raw (uncompensated) pressure level from the sensor." ]
Please provide a description of the function:def read_altitude(self, sealevel_pa=101325.0): # Calculation taken straight from section 3.6 of the datasheet. pressure = float(self.read_pressure()) altitude = 44330.0 * (1.0 - pow(pressure / sealevel_pa, (1.0/5.255))) self._logger.d...
[ "Calculates the altitude in meters." ]
Please provide a description of the function:def read_sealevel_pressure(self, altitude_m=0.0): pressure = float(self.read_pressure()) p0 = pressure / pow(1.0 - altitude_m/44330.0, 5.255) self._logger.debug('Sealevel pressure {0} Pa'.format(p0)) return p0
[ "Calculates the pressure at sealevel when given a known altitude in\n meters. Returns a value in Pascals." ]
Please provide a description of the function:def login_open_sheet(email, password, spreadsheet): try: gc = gspread.login(email, password) worksheet = gc.open(spreadsheet).sheet1 return worksheet except: print 'Unable to login and get spreadsheet. Check email, password, spreadsheet name.' sys.exit(1)
[ "Connect to Google Docs spreadsheet and return the first worksheet." ]
Please provide a description of the function:def _get_settings_class(): if not hasattr(django_settings, "AUTH_ADFS"): msg = "The configuration directive 'AUTH_ADFS' was not found in your Django settings" raise ImproperlyConfigured(msg) cls = django_settings.AUTH_ADFS.get('SETTINGS_CLASS', D...
[ "\n Get the AUTH_ADFS setting from the Django settings.\n " ]
Please provide a description of the function:def build_authorization_endpoint(self, request, disable_sso=None): self.load_config() redirect_to = request.GET.get(REDIRECT_FIELD_NAME, None) if not redirect_to: redirect_to = django_settings.LOGIN_REDIRECT_URL redirect_t...
[ "\n This function returns the ADFS authorization URL.\n\n Args:\n request(django.http.request.HttpRequest): A django Request object\n disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt.\n\n Returns:\n str: The r...
Please provide a description of the function:def vote(self, request, pk=None): choice = self.get_object() choice.vote() serializer = self.get_serializer(choice) return Response(serializer.data)
[ "\n post:\n A description of the post method on the custom action.\n " ]
Please provide a description of the function:def create_user(self, claims): # Create the user username_claim = settings.USERNAME_CLAIM usermodel = get_user_model() user, created = usermodel.objects.get_or_create(**{ usermodel.USERNAME_FIELD: claims[username_claim] ...
[ "\n Create the user if it doesn't exist yet\n\n Args:\n claims (dict): claims from the access token\n\n Returns:\n django.contrib.auth.models.User: A Django user\n " ]
Please provide a description of the function:def update_user_attributes(self, user, claims): required_fields = [field.name for field in user._meta.fields if field.blank is False] for field, claim in settings.CLAIM_MAPPING.items(): if hasattr(user, field): if claim ...
[ "\n Updates user attributes based on the CLAIM_MAPPING setting.\n\n Args:\n user (django.contrib.auth.models.User): User model instance\n claims (dict): claims from the access token\n " ]
Please provide a description of the function:def update_user_groups(self, user, claims): if settings.GROUPS_CLAIM is not None: # Update the user's group memberships django_groups = [group.name for group in user.groups.all()] if settings.GROUPS_CLAIM in claims: ...
[ "\n Updates user group memberships based on the GROUPS_CLAIM setting.\n\n Args:\n user (django.contrib.auth.models.User): User model instance\n claims (dict): Claims from the access token\n " ]
Please provide a description of the function:def update_user_flags(self, user, claims): if settings.GROUPS_CLAIM is not None: if settings.GROUPS_CLAIM in claims: access_token_groups = claims[settings.GROUPS_CLAIM] if not isinstance(access_token_groups, list):...
[ "\n Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.\n\n Args:\n user (django.contrib.auth.models.User): User model instance\n claims (dict): Claims from the access token\n " ]
Please provide a description of the function:def get(self, request): code = request.GET.get("code") if not code: # Return an error message return render(request, 'django_auth_adfs/login_failed.html', { 'error_message': "No authorization code was provided...
[ "\n Handles the redirect from ADFS to our site.\n We try to process the passed authorization code and login the user.\n\n Args:\n request (django.http.request.HttpRequest): A Django Request object\n " ]
Please provide a description of the function:def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provid...
[ "\n Returns a `User` if a correct access token has been supplied\n in the Authorization header. Otherwise returns `None`.\n " ]
Please provide a description of the function:def molecular_orbital(coords, mocoeffs, gbasis): '''Return a molecular orbital given the nuclei coordinates, as well as molecular orbital coefficients and basis set specification as given by the cclib library. The molecular orbital is represented as a func...
[]
Please provide a description of the function:def getbfs(coords, gbasis): sym2powerlist = { 'S' : [(0,0,0)], 'P' : [(1,0,0),(0,1,0),(0,0,1)], 'D' : [(2,0,0),(0,2,0),(0,0,2),(1,1,0),(0,1,1),(1,0,1)], 'F' : [(3,0,0),(2,1,0),(2,0,1),(1,2,0),(1,1,1),(1,0,2), (0,3,0),(...
[ "Convenience function for both wavefunction and density based on PyQuante Ints.py." ]
Please provide a description of the function:def S(a,b): if b.contracted: return sum(cb*S(pb,a) for (cb,pb) in b) elif a.contracted: return sum(ca*S(b,pa) for (ca,pa) in a) return a.norm*b.norm*overlap(a.exponent,a.powers, a.origin,b.exponent,b.powers,b....
[ "\n Simple interface to the overlap function.\n >>> from pyquante2 import pgbf,cgbf\n >>> s = pgbf(1)\n >>> isclose(S(s,s),1.0)\n True\n >>> sc = cgbf(exps=[1],coefs=[1])\n >>> isclose(S(sc,sc),1.0)\n True\n\n >>> sc = cgbf(exps=[1],coefs=[1])\n >>> isclose(S(sc,s),1.0)\n True\n ...
Please provide a description of the function:def T(a,b): if b.contracted: return sum(cb*T(pb,a) for (cb,pb) in b) elif a.contracted: return sum(ca*T(b,pa) for (ca,pa) in a) return a.norm*b.norm*kinetic(a.exponent,a.powers,a.origin, b.exponent,b.powers,b....
[ "\n Simple interface to the kinetic function.\n >>> from pyquante2 import pgbf,cgbf\n >>> from pyquante2.basis.pgbf import pgbf\n >>> s = pgbf(1)\n >>> isclose(T(s,s),1.5)\n True\n\n >>> sc = cgbf(exps=[1],coefs=[1])\n >>> isclose(T(sc,sc),1.5)\n True\n\n >>> sc = cgbf(exps=[1],coefs=[...
Please provide a description of the function:def V(a,b,C): if b.contracted: return sum(cb*V(pb,a,C) for (cb,pb) in b) elif a.contracted: return sum(ca*V(b,pa,C) for (ca,pa) in a) return a.norm*b.norm*nuclear_attraction(a.exponent,a.powers,a.origin, ...
[ "\n Simple interface to the nuclear attraction function.\n >>> from pyquante2 import pgbf,cgbf\n >>> s = pgbf(1)\n >>> isclose(V(s,s,(0,0,0)),-1.595769)\n True\n\n >>> sc = cgbf(exps=[1],coefs=[1])\n >>> isclose(V(sc,sc,(0,0,0)),-1.595769)\n True\n\n >>> sc = cgbf(exps=[1],coefs=[1])\n ...
Please provide a description of the function:def overlap(alpha1,lmn1,A,alpha2,lmn2,B): l1,m1,n1 = lmn1 l2,m2,n2 = lmn2 rab2 = norm2(A-B) gamma = alpha1+alpha2 P = gaussian_product_center(alpha1,A,alpha2,B) pre = pow(pi/gamma,1.5)*exp(-alpha1*alpha2*rab2/gamma) wx = overlap1d(l1,l2,P[0...
[ "\n Full form of the overlap integral. Taken from THO eq. 2.12\n >>> isclose(overlap(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d')),1.968701)\n True\n " ]
Please provide a description of the function:def overlap1d(l1,l2,PAx,PBx,gamma): total = 0 for i in range(1+int(floor(0.5*(l1+l2)))): total += binomial_prefactor(2*i,l1,l2,PAx,PBx)* \ fact2(2*i-1)/pow(2*gamma,i) return total
[ "\n The one-dimensional component of the overlap integral. Taken from THO eq. 2.12\n >>> isclose(overlap1d(0,0,0,0,1),1.0)\n True\n " ]
Please provide a description of the function:def gaussian_product_center(alpha1,A,alpha2,B): return (alpha1*A+alpha2*B)/(alpha1+alpha2)
[ "\n The center of the Gaussian resulting from the product of two Gaussians:\n >>> gaussian_product_center(1,array((0,0,0),'d'),1,array((0,0,0),'d'))\n array([ 0., 0., 0.])\n " ]
Please provide a description of the function:def binomial_prefactor(s,ia,ib,xpa,xpb): total= 0 for t in range(s+1): if s-ia <= t <= ib: total += binomial(ia,s-t)*binomial(ib,t)* \ pow(xpa,ia-s+t)*pow(xpb,ib-t) return total
[ "\n The integral prefactor containing the binomial coefficients from Augspurger and Dykstra.\n >>> binomial_prefactor(0,0,0,0,0)\n 1\n " ]
Please provide a description of the function:def kinetic(alpha1,lmn1,A,alpha2,lmn2,B): l1,m1,n1 = lmn1 l2,m2,n2 = lmn2 term0 = alpha2*(2*(l2+m2+n2)+3)*\ overlap(alpha1,(l1,m1,n1),A,\ alpha2,(l2,m2,n2),B) term1 = -2*pow(alpha2,2)*\ (overlap(alpha1,(...
[ "\n The full form of the kinetic energy integral\n >>> isclose(kinetic(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d')),2.953052)\n True\n " ]
Please provide a description of the function:def nuclear_attraction(alpha1,lmn1,A,alpha2,lmn2,B,C): l1,m1,n1 = lmn1 l2,m2,n2 = lmn2 gamma = alpha1+alpha2 P = gaussian_product_center(alpha1,A,alpha2,B) rab2 = norm2(A-B) rcp2 = norm2(C-P) dPA = P-A dPB = P-B dPC = P-C Ax = ...
[ "\n Full form of the nuclear attraction integral\n >>> isclose(nuclear_attraction(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d'),array((0,0,0),'d')),-3.141593)\n True\n " ]
Please provide a description of the function:def A_term(i,r,u,l1,l2,PAx,PBx,CPx,gamma): return pow(-1,i)*binomial_prefactor(i,l1,l2,PAx,PBx)*\ pow(-1,u)*factorial(i)*pow(CPx,i-2*r-2*u)*\ pow(0.25/gamma,r+u)/factorial(r)/factorial(u)/factorial(i-2*r-2*u)
[ "\n THO eq. 2.18\n\n >>> A_term(0,0,0,0,0,0,0,0,1)\n 1.0\n >>> A_term(0,0,0,0,1,1,1,1,1)\n 1.0\n >>> A_term(1,0,0,0,1,1,1,1,1)\n -1.0\n >>> A_term(0,0,0,1,1,1,1,1,1)\n 1.0\n >>> A_term(1,0,0,1,1,1,1,1,1)\n -2.0\n >>> A_term(2,0,0,1,1,1,1,1,1)\n 1.0\n >>> A_term(2,0,1,1,1,1,...
Please provide a description of the function:def A_array(l1,l2,PA,PB,CP,g): Imax = l1+l2+1 A = [0]*Imax for i in range(Imax): for r in range(int(floor(i/2)+1)): for u in range(int(floor((i-2*r)/2)+1)): I = i-2*r-u A[I] = A[I] + A_term(i,r,u,l1,l2,PA,P...
[ "\n THO eq. 2.18 and 3.1\n\n >>> A_array(0,0,0,0,0,1)\n [1.0]\n >>> A_array(0,1,1,1,1,1)\n [1.0, -1.0]\n >>> A_array(1,1,1,1,1,1)\n [1.5, -2.5, 1.0]\n " ]
Please provide a description of the function:def mesh(self,xyzs): I,J,K = self.powers d = np.asarray(xyzs,'d')-self.origin # Got help from stackoverflow user @unutbu with this. # See: http://stackoverflow.com/questions/17391052/compute-square-distances-from-numpy-array d...
[ "\n Evaluate basis function on a mesh of points *xyz*.\n " ]
Please provide a description of the function:def _normalize(self): "Normalize basis function. From THO eq. 2.2" l,m,n = self.powers self.norm = np.sqrt(pow(2,2*(l+m+n)+1.5)* pow(self.exponent,l+m+n+1.5)/ fact2(2*l-1)/fact2(2*m-1)/ ...
[]
Please provide a description of the function:def select(self, selections): '''Make a selection in this representation. BallAndStickRenderer support selections of atoms and bonds. To select the first atom and the first bond you can use the following code:: ...
[]
Please provide a description of the function:def hide(self, selections): '''Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer...
[]
Please provide a description of the function:def scale(self, selections, factor): '''Scale the objects represented by *selections* up to a certain *factor*. ''' if 'atoms' in selections: atms = selections['atoms'].mask if factor is None: self....
[]
Please provide a description of the function:def change_radius(self, selections, value): '''Change the radius of each atom by a certain value ''' if 'atoms' in selections: atms = selections['atoms'].mask if value is None: self.radii_state.array[at...
[]
Please provide a description of the function:def change_color(self, selections, value): '''Change the color of each atom by a certain value. *value* should be a tuple. ''' if 'atoms' in selections: atms = selections['atoms'].mask if value is None: ...
[]
Please provide a description of the function:def paintGL(self): '''GL function called each time a frame is drawn''' if self.post_processing: # Render to the first framebuffer glBindFramebuffer(GL_FRAMEBUFFER, self.fb0) glViewport(0, 0, self.width(), self.height()) ...
[]
Please provide a description of the function:def toimage(self, width=None, height=None): '''Return the current scene as a PIL Image. **Example** You can build your molecular viewer as usual and dump an image at any resolution supported by the video card (up to the memory limits...
[]
Please provide a description of the function:def sto(zeta,N=1,L=0,M=0,origin=(0,0,0)): nlm2powers = { (1,0,0) : (0,0,0,0), # x,y,z,r (2,0,0) : (0,0,0,1), (3,0,0) : (0,0,0,2), (2,1,0) : (1,0,0,0), (2,1,1) : (0,1,0,0), (2,1,-1) : (0,0,1,0), (3,1,0) : (1,0...
[ "\n Use Stewarts STO-6G fits to create a contracted Gaussian approximation to a\n Slater function. Fits of other expansion lengths (1G, 3G, etc) are in the paper.\n\n Reference: RF Stewart, JCP 52, 431 (1970)\n\n >>> s = sto(1)\n >>> np.isclose(s(0,0,0),0.530121)\n True\n " ]
Please provide a description of the function:def mesh(self,xyzs): return sum(c*p.mesh(xyzs) for c,p in self)
[ "\n Evaluate basis function on a mesh of points *xyz*.\n " ]
Please provide a description of the function:def _real(coords1, charges1, coords2, charges2, rcut, alpha, box): n = coords1.shape[0] m = coords2.shape[0] # Unit vectors a = box[0] b = box[1] c = box[2] # This is helpful to add the correct number of boxes l_max = int(np.cei...
[ "Calculate ewald real part. Box has to be a cuboidal box you should\n transform any other box shape to a cuboidal box before using this.\n \n " ]
Please provide a description of the function:def _reciprocal(coords1, charges1, coords2, charges2, kmax, kappa, box): n = coords1.shape[0] m = coords2.shape[0] result = np.zeros(n, dtype=np.float64) need_self = np.zeros(n, dtype=np.uint8) # Reciprocal unit vectors g1, g2, g3 = reciprocal_v...
[ "Calculate ewald reciprocal part. Box has to be a cuboidal box you should\n transform any other box shape to a cuboidal box before using this.\n \n " ]
Please provide a description of the function:def update_bounds(self, bounds): '''Update cylinders start and end positions ''' starts = bounds[:,0,:] ends = bounds[:,1,:] self.bounds = bounds self.lengths = np.sqrt(((ends - starts)**2).sum(axis=1)) ver...
[]
Please provide a description of the function:def make_trajectory(first, filename, restart=False): '''Factory function to easily create a trajectory object''' mode = 'w' if restart: mode = 'a' return Trajectory(first, filename, mode)
[]
Please provide a description of the function:def compileShader( source, shaderType ): if isinstance(source, str): source = [source] elif isinstance(source, bytes): source = [source.decode('utf-8')] shader = glCreateShader(shaderType) glShaderSource(shader, source) glCompile...
[ "Compile shader source of given type\n \n source -- GLSL source-code for the shader\n shaderType -- GLenum GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, etc,\n \n returns GLuint compiled shader reference\n raises RuntimeError when a compilation failure occurs\n ", "Shader compile failure (%s): %s" ]
Please provide a description of the function:def has_key(self, key): k = self._lowerOrReturn(key) return k in self.data
[ "Case insensitive test whether 'key' exists." ]
Please provide a description of the function:def update(self, dict): for k,v in dict.items(): self[k] = v
[ "Copy (key,value) pairs from 'dict'." ]
Please provide a description of the function:def update_positions(self, positions): '''Update the sphere positions. ''' sphs_verts = self.sphs_verts_radii.copy() sphs_verts += positions.reshape(self.n_spheres, 1, 3) self.tr.update_vertices(sphs_verts) self.poslist = posi...
[]
Please provide a description of the function:def query_ball_point(self, x, r, p=2., eps=0): x = np.asarray(x).astype(np.float) if x.shape[-1] != self.m: raise ValueError("Searching for a %d-dimensional point in a " \ "%d-dimensional KDTree" % (x.shape[-1...
[ "\n Find all points within distance r of point(s) x.\n\n Parameters\n ----------\n x : array_like, shape tuple + (self.m,)\n The point or points to search for neighbors of.\n r : positive float\n The radius of points to return.\n p : float, optional\n ...
Please provide a description of the function:def isnamedtuple(obj): return isinstance(obj, tuple) \ and hasattr(obj, "_fields") \ and hasattr(obj, "_asdict") \ and callable(obj._asdict)
[ "Heuristic check if an object is a namedtuple." ]
Please provide a description of the function:def display_molecule(mol, style='ball-and-stick'): '''Display the molecule *mol* with the default viewer. ''' v = QtViewer() if style == 'ball-and-stick': bs = v.add_renderer(BallAndStickRenderer, mol.r_array, ...
[]
Please provide a description of the function:def display_system(sys, style='vdw'): '''Display the system *sys* with the default viewer. ''' v = QtViewer() #v.add_post_processing(FXAAEffect) v.add_post_processing(SSAOEffect) if style == 'vdw': sr = v.add_renderer(AtomRende...
[]
Please provide a description of the function:def display_trajectory(sys, times, coords_list, box_vectors=None, style='spheres'): '''Display the the system *sys* and instrument the trajectory viewer with frames information. .. image:: /_static/display_trajectory.png **Par...
[]
Please provide a description of the function:def running_coordination_number(coordinates_a, coordinates_b, periodic, binsize=0.002, cutoff=1.5): x, y = rdf(coordinates_a, coordinates_b, periodic=periodic, normalize=False, ...
[ "This is the cumulative radial distribution \n function, also called running coordination number" ]
Please provide a description of the function:def update_colors(self, colors): colors = np.array(colors, dtype=np.uint8) self._vbo_c.set_data(colors) self._vbo_c.unbind()
[ "Update the colors" ]
Please provide a description of the function:def trajectory(start=None, stop=None, step=None): '''Useful command to iterate on the trajectory frames by time (in ns). It is meant to be used in a for loop:: for i in trajectory(0, 10, 0.1): coords = current_frame() t = current_time...
[]
Please provide a description of the function:def frames(skip=1): '''Useful command to iterate on the trajectory frames. It can be used in a for loop. :: for i in frames(): coords = current_trajectory()[i] # Do operation on coords You can use the option *skip* to ta...
[]
Please provide a description of the function:def display_system(system, autozoom=True): '''Display a `~chemlab.core.System` instance at screen''' viewer.clear() viewer.add_representation(BallAndStickRepresentation, system) if autozoom: autozoom_() viewer.update() msg(str(system))
[]
Please provide a description of the function:def display_molecule(mol, autozoom=True): '''Display a `~chemlab.core.Molecule` instance in the viewer. This function wraps the molecule in a system before displaying it. ''' s = System([mol]) display_system(s, autozoom=True)
[]