text
stringlengths
78
104k
score
float64
0
0.18
def render(self, context): """Render.""" try: from django.core.urlresolvers import reverse except ImportError: # pylint: disable=no-name-in-module, import-error from django.urls import reverse # Check if we have real or Django static-served media ...
0.003263
def add_wic(self, old_wic, wic): """ Convert the old style WIC slot to a new style WIC slot and add the WIC to the node properties :param str old_wic: Old WIC slot :param str wic: WIC name """ new_wic = 'wic' + old_wic[-1] self.node['properties'][new_wic]...
0.006135
def __parse_relation(): '''Gets and parses file''' relation_filename = get_file('relation.tsv') vertice_filename = get_file('vertice.tsv') relation_textfile = open(relation_filename, 'r') vertice_textfile = open(vertice_filename, 'r') # Parse vertice: vertices = {} next(vertice_textfil...
0.000884
def _create_client(self, clt_class, url, public=True, special=False): """ Creates a client instance for the service. """ if self.service == "compute" and not special: # Novaclient requires different parameters. client = pyrax.connect_to_cloudservers(region=self.re...
0.006504
def try_one_generator (project, name, generator, target_type, properties, sources): """ Checks if generator invocation can be pruned, because it's guaranteed to fail. If so, quickly returns empty list. Otherwise, calls try_one_generator_really. """ if __debug__: from .targets import ...
0.017808
def get_grade_entries_on_date(self, from_, to): """Gets a ``GradeEntryList`` effective during the entire given date range inclusive but not confined to the date range. arg: from (osid.calendaring.DateTime): start of date range arg: to (osid.calendaring.DateTime): end of date range ...
0.003484
def hide_arp_holder_arp_entry_interfacetype_Ve_Ve(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp") arp_entry = ET.SubElement(hide_arp_holder, "arp-entry")...
0.004098
def get_unique_name(self, cursor): """get the spelling or create a unique name for a cursor""" name = '' if cursor.kind in [CursorKind.UNEXPOSED_DECL]: return '' # covers most cases name = cursor.spelling # if its a record decl or field decl and its type is un...
0.010658
def _iso_handler(obj): """ Transforms an object into it's ISO format, if possible. If the object can't be transformed, then an error is raised for the JSON parser. This is meant to be used on datetime instances, but will work with any object having a method called isoformat. :param obj: o...
0.00303
def create_organization(organization): """ Inserts a new organization into app/local state given the following dictionary: { 'name': string, 'description': string } Returns an updated dictionary including a new 'id': integer field/value """ # Trust, but verify... if not o...
0.003314
def binarize(x, values, threshold=None, included_in='upper'): """Binarizes the values of x. Parameters ---------- values : tuple of two floats The lower and upper value to which the inputs are mapped. threshold : float The threshold; defaults to (values[0] + values[1]) / 2 if None. ...
0.001189
def walk_files_for(paths, supported_extensions): """ Iterating files for given extensions. Args: supported_extensions (list): supported file extentsion for which to check loc and com. Returns: str: yield each full path and filename found. """ for...
0.004184
def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value ...
0.004376
def __safe_validation_callback(self, event): # type: (str) -> Any """ Calls the ``@ValidateComponent`` or ``@InvalidateComponent`` callback, ignoring raised exceptions :param event: The kind of life-cycle callback (in/validation) :return: The callback result, or None ...
0.002686
def add_external_reference_to_entity(self,entity_id,ext_ref): """ Adds an external reference to a entity specified by the entity identifier @param entity_id: the entity identifier @type entity_id: string @param ext_ref: the external reference @type ext_ref: L{CexternalRef...
0.014837
def mouseReleaseEvent(self, event): """Create a new event or marker, or show the previous power spectrum """ if not self.scene: return if self.event_sel: return if self.deselect: self.deselect = False return if not self.r...
0.001936
def transpose(self, rows): """ Transposes the grid to allow for cols """ res = OrderedDict() for row, cols in rows.items(): for col, cell in cols.items(): if col not in res: res[col] = OrderedDict() res[col][row] = c...
0.005848
def set_raw(self, *args): """ writes all *args as styled commands 'm' to the handle """ if not self.enabled: return args = map(lambda x: str(x), [x for x in args if x is not None]) self._write_raw(';'.join(args) + 'm')
0.011278
def get_console_info(kernel32, handle): """Get information about this current console window. http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231 https://code.google.com/p/colorama/issues/detail?id=47 https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py Windows 10...
0.004172
def findArgs(args, prefixes): """ Extracts the list of arguments that start with any of the specified prefix values """ return list([ arg for arg in args if len([p for p in prefixes if arg.lower().startswith(p.lower())]) > 0 ])
0.041152
def _generate_time_steps(self, trajectory_list): """A generator to yield single time-steps from a list of trajectories.""" for single_trajectory in trajectory_list: assert isinstance(single_trajectory, trajectory.Trajectory) # Skip writing trajectories that have only a single time-step -- this ...
0.008961
def select_torrent(self): """Select torrent. First check if specific element/info is obtained in content_page. Specify to user if it wants best rated torrent or select one from list. If the user wants best rated: Directly obtain magnet/torrent. Else: build table with all data an...
0.001762
def write(self, proto): """Populate serialization proto instance. :param proto: (TemporalMemoryShimProto) the proto instance to populate """ super(TemporalMemoryShim, self).write(proto.baseTM) proto.connections.write(self.connections) proto.predictiveCells = self.predictiveCells
0.003289
def update(self): """It updates process information of the cgroup.""" pids = fileops.readlines(self.paths['cgroup.procs']) self.pids = [int(pid) for pid in pids if pid != ''] self.n_procs = len(pids)
0.008658
def areIndicesValid(self, inds): """ Test if indices are valid @param inds index set @return True if valid, False otherwise """ return reduce(operator.and_, [0 <= inds[d] < self.dims[d] for d in range(self.ndims)], True)
0.006536
def ParseFileHash(hash_obj, result): """Parses Hash rdfvalue into ExportedFile's fields.""" if hash_obj.HasField("md5"): result.hash_md5 = str(hash_obj.md5) if hash_obj.HasField("sha1"): result.hash_sha1 = str(hash_obj.sha1) if hash_obj.HasField("sha256"): result.hash_sha256 = str(ha...
0.009777
def write_records(records, output_file, split=False): """Write FASTA records Write a FASTA file from an iterable of records. Parameters ---------- records : iterable Input records to write. output_file : file, str or pathlib.Path Output FASTA file to be written into. split...
0.001383
def generate_all_paired_mutations_for_position(self, chain_ids, chain_sequence_mappings = {}, residue_ids_to_ignore = [], typed_residue_ids_to_ignore = [], silent = True): '''Generates a set of mutations for the chains in chain_ids where each set corresponds to the "same" residue (see below) in both ...
0.008022
def screenshot(self): """ Take screenshot with session check Returns: PIL.Image """ b64data = self.http.get('/screenshot').value raw_data = base64.b64decode(b64data) from PIL import Image buff = io.BytesIO(raw_data) return Image.open(b...
0.006173
def create(self, ip_access_control_list_sid): """ Create a new IpAccessControlListInstance :param unicode ip_access_control_list_sid: The SID of the IP Access Control List that you want to associate with the trunk :returns: Newly created IpAccessControlListInstance :rtype: twil...
0.008368
def redirect_to(request, url, permanent=True, query_string=False, **kwargs): r""" Redirect to a given URL. The given url may contain dict-style string formatting, which will be interpolated against the params in the URL. For example, to redirect from ``/foo/<id>/`` to ``/bar/<id>/``, you could use...
0.000705
def update(self, data=None, timeout=-1, force=''): """Updates server profile template. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops wa...
0.003382
def proto_unknown(theABF): """protocol: unknown.""" abf=ABF(theABF) abf.log.info("analyzing as an unknown protocol") plot=ABFplot(abf) plot.rainbow=False plot.title=None plot.figure_height,plot.figure_width=SQUARESIZE,SQUARESIZE plot.kwargs["lw"]=.5 plot.figure_chronological() pl...
0.027907
def opening(image, radius=None, mask=None, footprint=None): '''Do a morphological opening image - pixel image to operate on radius - use a structuring element with the given radius. If no radius, use an 8-connected structuring element. mask - if present, only use unmasked pixels for op...
0.00431
def xlsx_blob(self): """ Return the byte stream of an Excel file formatted as chart data for the category chart specified in the chart data object. """ xlsx_file = BytesIO() with self._open_worksheet(xlsx_file) as (workbook, worksheet): self._populate_workshee...
0.005291
def make_pvc( name, storage_class, access_modes, storage, labels=None, annotations=None, ): """ Make a k8s pvc specification for running a user notebook. Parameters ---------- name: Name of persistent volume claim. Must be unique within the namespace the object is ...
0.003125
def show_slug_with_level(context, page, lang=None, fallback=True): """Display slug with level by language.""" if not lang: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' return {'content': page.s...
0.002933
def _convert_volume(self, volume): """ This is for ingesting the "volumes" of a app description """ data = { 'host': volume.get('hostPath'), 'container': volume.get('containerPath'), 'readonly': volume.get('mode') == 'RO', } return data
0.00625
def update(self, instance_id: str, details: UpdateDetails, async_allowed: bool) -> UpdateServiceSpec: """ Further readings `CF Broker API#Update <https://docs.cloudfoundry.org/services/api.html#updating_service_instance>`_ :param instance_id: Instance id provided by the platform :param ...
0.00692
def hill_climbing(problem, iterations_limit=0, viewer=None): ''' Hill climbing search. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: SearchProblem.actions, Search...
0.001565
def connect(self): """Create new connection unless we already have one.""" if not getattr(self._local, 'conn', None): try: server = self._servers.get() logger.debug('Connecting to %s', server) self._local.conn = ClientTransport(server, self._fr...
0.00625
def edges(self, zfill = 3): """ Returns the aspect ratio of all elements. """ edges = self.split("edges", at = "coords").unstack() edges["lx"] = edges.x[1]-edges.x[0] edges["ly"] = edges.y[1]-edges.y[0] edges["lz"] = edges.z[1]-edges.z[0] edges["l"] = np.linalg.norm(edges[["lx", "ly", "l...
0.022021
def WeightedLearner(unweighted_learner): """Given a learner that takes just an unweighted dataset, return one that takes also a weight for each example. [p. 749 footnote 14]""" def train(dataset, weights): return unweighted_learner(replicated_dataset(dataset, weights)) return train
0.003268
def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name...
0.003125
def set(self, value, mode=None): """Sets metric value. :param int|long value: New value. :param str|unicode mode: Update mode. * None - Unconditional update. * max - Sets metric value if it is greater that the current one. * min - Sets metric value if it is...
0.003295
def cleanup_logger(self): """Clean up logger to close out file handles. After this is called, writing to self.log will get logs ending up getting discarded. """ self.log_handler.close() self.log.removeHandler(self.log_handler)
0.007273
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])...
0.002959
def list(self, language=values.unset, model_build=values.unset, status=values.unset, limit=None, page_size=None): """ Lists QueryInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. ...
0.007383
def LayerTree_loadSnapshot(self, tiles): """ Function path: LayerTree.loadSnapshot Domain: LayerTree Method name: loadSnapshot Parameters: Required arguments: 'tiles' (type: array) -> An array of tiles composing the snapshot. Returns: 'snapshotId' (type: SnapshotId) -> The id of the snap...
0.045313
def get_grade_system_admin_session(self): """Gets the ``OsidSession`` associated with the grade system administration service. return: (osid.grading.GradeSystemAdminSession) - a ``GradeSystemAdminSession`` raise: OperationFailed - unable to complete request raise: Unim...
0.00411
def _parse_header_links(response): """ Parse the links from a Link: header field. .. todo:: Links with the same relation collide at the moment. :param bytes value: The header value. :rtype: `dict` :return: A dictionary of parsed links, keyed by ``rel`` or ``url``. """ values = respon...
0.000864
def get_proj_info(self, token): """ Return the project info for a given token. Arguments: token (str): Token to return information for Returns: JSON: representation of proj_info """ r = self.remote_utils.get_url(self.url() + "{}/info/".format(tok...
0.005747
def post(self, command, data=None): """Post data to API.""" now = calendar.timegm(datetime.datetime.now().timetuple()) if now > self.expiration: auth = self.__open("/oauth/token", data=self.oauth) self.__sethead(auth['access_token']) return self.__open("%s%s" % (s...
0.005063
def auth(self, request): """ build the request to access to the Twitter website with all its required parms :param request: makes the url to call Twitter + the callback url :return: go to the Twitter website to ask to the user to allow the access of TriggerHappy "...
0.002782
def visit_keyword(self, node): """ Process keyword arguments. """ if self.should_check_whitelist(node): if node.arg not in self.whitelist and not node.arg.startswith("debug_"): self.violations.append((self.current_logging_call, WHITELIST_VIOLATION.format(node...
0.00823
def negated(input_words, include_nt=True): """ Determine if input contains negation words """ input_words = [str(w).lower() for w in input_words] neg_words = [] neg_words.extend(NEGATE) for word in neg_words: if word in input_words: return True if include_nt: ...
0.001779
def empty_hdf5_file(h5f, ifo=None): """Determine whether PyCBC-HDF5 file is empty A file is considered empty if it contains no groups at the base level, or if the ``ifo`` group contains only the ``psd`` dataset. Parameters ---------- h5f : `str` path of the pycbc_live file to test ...
0.001153
def if_sqlserver_disable_constraints_triggers(session: SqlASession, tablename: str) -> None: """ If we're running under SQL Server, disable triggers AND constraints for the specified table while the resource is held. Args: session: SQLAlchemy :class...
0.001949
def rollforward(self, dt): """ Roll provided date forward to next offset only if not on offset. """ if not self.onOffset(dt): if self.n >= 0: return self._next_opening_time(dt) else: return self._prev_opening_time(dt) return...
0.006192
def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log("info", " * Restarting with %s" % self.name) args = _get_args_for_reloading() # a weird bug on w...
0.001753
def extract_value(self, data): """Extract the id key and validate the request structure.""" errors = [] if 'id' not in data: errors.append('Must have an `id` field') if 'type' not in data: errors.append('Must have a `type` field') elif data['type'] != self...
0.002918
def load(s, **kwargs): """Load yaml file""" try: return loads(s, **kwargs) except TypeError: return loads(s.read(), **kwargs)
0.006536
def load_csv_to_model(path, model, field_names=None, delimiter=None, batch_len=10000, dialect=None, num_header_rows=1, mode='rUb', strip=True, clear=False, dry_run=True, ignore_errors=True, verbosity=2): '''Bulk create database records from batches of rows in a csv file....
0.004946
def get_kernel_string(kernel_source, params=None): """ retrieve the kernel source and return as a string This function processes the passed kernel_source argument, which could be a function, a string with a filename, or just a string with code already. If kernel_source is a function, the function is c...
0.00303
def setRect(self, rect): """ Sets the window bounds from a tuple of (x,y,w,h) """ self.x, self.y, self.w, self.h = rect
0.047244
def fuzzer(buffer, fuzz_factor=101): """Fuzz given buffer. Take a buffer of bytes, create a copy, and replace some bytes with random values. Number of bytes to modify depends on fuzz_factor. This code is taken from Charlie Miller's fuzzer code. :param buffer: the data to fuzz. :type buffer: by...
0.001357
def channels_open(self, room_id, **kwargs): """Adds the channel back to the user’s list of channels.""" return self.__call_api_post('channels.open', roomId=room_id, kwargs=kwargs)
0.015385
def initial(self, request, *args, **kwargs): """Disallow users other than the user whose email is being reset.""" email = request.data.get('email') if request.user.is_authenticated() and email != request.user.email: raise PermissionDenied() return super(ResendConfirmationEma...
0.00489
def chrono(ctx, app_id, sentence_file, json_flag, sentence, doc_time, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """Extract expression expressing date and time and normalize its value """ app_id = clean_app_id(app_id) sentence = cle...
0.001453
def excepthook(type, value, tb): """Report an exception.""" if (issubclass(type, Error) or issubclass(type, lib50.Error)) and str(value): for line in str(value).split("\n"): cprint(str(line), "yellow") else: cprint(_("Sorry, something's wrong! Let sysadmins@cs50.harvard.edu know!...
0.006536
def _convert(self, desired_type: Type[T], source_obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Delegates to the user-provided method. Passes the appropriate part of the options according to the function name. :param desired_type: :param source_obj: ...
0.006803
def make_converters(data_types) -> dict: """ Return a mapping between data type names, and casting functions, or class definitions to convert text into its Python object. Parameters ---------- data_types: dict-like data field name str: python primitive type or class. Example ----...
0.001821
def adjoint(self): r"""Return the (right) adjoint. Notes ----- Due to technicalities of operators from a real space into a complex space, this does not satisfy the usual adjoint equation: .. math:: \langle Ax, y \rangle = \langle x, A^*y \rangle Ins...
0.001085
def containerIsRunning(name_or_id): '''Check if container with the given name or ID (str) is running. No side effects. Idempotent. Returns True if running, False if not.''' require_str("name_or_id", name_or_id) try: container = getContainer(name_or_id) # Refer to the latest status list ...
0.008507
def df_random(num_numeric=3, num_categorical=3, num_rows=100): """Generate a dataframe with random data. This is a general method to easily generate a random dataframe, for more control of the random 'distributions' use the column methods (df_numeric_column, df_categorical_column) For other dis...
0.0045
def transform(self, X, y=None): """Transform data by adding two virtual features. Parameters ---------- X: numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples and n_components is the number of components. y: None ...
0.00216
def isscalar(cls, dataset, dim): """ Tests if dimension is scalar in each subpath. """ if not dataset.data: return True ds = cls._inner_dataset_template(dataset) isscalar = [] for d in dataset.data: ds.data = d isscalar.append(d...
0.005277
def extrusion(target, throat_length='throat.length', throat_area='throat.area'): r""" Calculate throat volume from the throat area and the throat length. This method is useful for abnormal shaped throats. Parameters ---------- target : OpenPNM Object The object which this ...
0.001134
def decode(self, envelope, session, target=None, modification_code=None, **kwargs): """ Methods checks envelope for 'modification_code' existence and removes it. :param envelope: original envelope :param session: original session :param target: flag, that specifies whether code must be searched and removed at ...
0.020322
def _From(self, t): """ Handle "from xyz import foo, bar as baz". """ # fixme: Are From and ImportFrom handled differently? self._fill("from ") self._write(t.modname) self._write(" import ") for i, (name,asname) in enumerate(t.names): if i != 0: ...
0.006593
def decode_from_file(estimator, filename, hparams, decode_hp, decode_to_file=None, checkpoint_path=None): """Compute predictions on entries in filename and write them out.""" if not decode_hp.batch_size: dec...
0.011959
def Bernoulli(p, tag=None): """ A Bernoulli random variate Parameters ---------- p : scalar The probability of success """ assert ( 0 < p < 1 ), 'Bernoulli probability "p" must be between zero and one, non-inclusive' return uv(ss.bernoulli(p), tag=tag)
0.006472
def randomwif(prefix, num): """ Obtain a random private/public key pair """ from bitsharesbase.account import PrivateKey t = [["wif", "pubkey"]] for n in range(0, num): wif = PrivateKey() t.append([str(wif), format(wif.pubkey, prefix)]) print_table(t)
0.003425
def stop(self): """ Instructs the kernel process to stop channels and the kernel manager to then shutdown the process. """ logger.debug('Stopping kernel') self.kc.stop_channels() self.km.shutdown_kernel(now=True) del self.km
0.006944
def calf(self, spec): """ Typical safe usage is this, which sets everything that could be problematic up. Requires the filename which everything will be produced to. """ if not isinstance(spec, Spec): raise TypeError('spec must be of type Spec') if ...
0.001301
def get_subreddit(self, subreddit_name, *args, **kwargs): """Return a Subreddit object for the subreddit_name specified. The additional parameters are passed directly into the :class:`.Subreddit` constructor. """ sr_name_lower = subreddit_name.lower() if sr_name_lower =...
0.00365
def axis_updated(self, event: InputEvent, prefix=None): """ Called to process an absolute axis event from evdev, this is called internally by the controller implementations :internal: :param event: The evdev event to process :param prefix: If present, a ...
0.006443
def chk_edges(self): """Check that all edge nodes exist in local subset.""" goids = set(self.go2obj) self.chk_edges_nodes(self.edges, goids, "is_a") for reltype, edges in self.edges_rel.items(): self.chk_edges_nodes(edges, goids, reltype)
0.007092
def fieldinfo(self): """Retrieve info about all vdata fields. Args:: no argument Returns:: list where each element describes a field of the vdata; each field is described by an 7-element tuple containing the following elements: - field name ...
0.001976
def _generate_initial_model(self): """Creates the initial model for the optimistation. Raises ------ TypeError Raised if the model failed to build. This could be due to parameters being passed to the specification in the wrong format. """ ...
0.001921
def quote_edge(identifier): """Return DOT edge statement node_id from string, quote if needed. >>> quote_edge('spam') 'spam' >>> quote_edge('spam spam:eggs eggs') '"spam spam":"eggs eggs"' >>> quote_edge('spam:eggs:s') 'spam:eggs:s' """ node, _, rest = identifier.partition(':') ...
0.001931
def copyfile(source, destination, force=True): '''copy a file from a source to its destination. ''' if os.path.exists(destination) and force is True: os.remove(destination) shutil.copyfile(source, destination) return destination
0.003906
def Stat(self, urns): """Returns metadata about all urns. Currently the metadata include type, and last update time. Args: urns: The urns of the objects to open. Yields: A dict of metadata. Raises: ValueError: A string was passed instead of an iterable. """ if isinstanc...
0.010767
def report(self, item_id, report_format="json"): """Retrieves the specified report for the analyzed item, referenced by item_id. Available formats include: json, html, all, dropped, package_files. :type item_id: int :param item_id: Task ID number :type report_form...
0.004032
def has_external_dependency(name): 'Check that a non-Python dependency is installed.' for directory in os.environ['PATH'].split(':'): if os.path.exists(os.path.join(directory, name)): return True return False
0.004167
def get_id2parents(objs): """Get all parent item IDs for each item in dict keys.""" id2parents = {} for obj in objs: _get_id2parents(id2parents, obj.item_id, obj) return id2parents
0.004902
def get(self, key, default=None, with_age=False): " Return the value for key if key is in the dictionary, else default. " try: return self.__getitem__(key, with_age) except KeyError: if with_age: return default, None else: retur...
0.006079
def expert_to_gates(self): """Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.float32` and shapes `[expert_batch_size_i]` """ return tf.split( self._nonzero_gates, self._part_sizes_te...
0.002849
def get_oauth_url(self): """ Returns the URL with OAuth params """ params = OrderedDict() if "?" in self.url: url = self.url[:self.url.find("?")] for key, value in parse_qsl(urlparse(self.url).query): params[key] = value else: url = se...
0.002805
def principal_axis_system(self): """ Returns a chemical shielding tensor aligned to the principle axis system so that only the 3 diagnol components are non-zero """ return ChemicalShielding(np.diag(np.sort(np.linalg.eigvals(self))))
0.011029