code
stringlengths
1
18.2k
def get_binding(self, schema, data): """ For a given schema, get a binding mediator providing links to the RDF terms matching that schema. """ schema = self.parent.get_schema(schema) return Binding(schema, self.parent.resolver, data=data)
def get(self, id, depth=3, schema=None): """ Construct a single object based on its ID. """ uri = URIRef(id) if schema is None: for o in self.graph.objects(subject=uri, predicate=RDF.type): schema = self.parent.get_schema(str(o)) if schema is not None: break else: schema = self.parent.get_schema(schema) binding = self....
def _objectify(self, node, binding, depth, path): """ Given an RDF node URI (and it's associated schema), return an object from the ``graph`` that represents the information available about this node. """ if binding.is_object: obj = {'$schema': binding.path} for (s, p, o) in self.graph.triples((node, None, None)): prop...
def get_text_node(self, tree, xpath_str): """Return a text node from given XML tree given an lxml XPath.""" try: text = tree.xpath(xpath_str, namespaces=self.namespaces)[0].text return text_type(text) if text else '' except IndexError: # pragma: nocover return ''
def get_subtree(self, tree, xpath_str): """Return a subtree given an lxml XPath.""" return tree.xpath(xpath_str, namespaces=self.namespaces)
def fundertree2json(self, tree, oai_id): """Convert OpenAIRE's funder XML to JSON.""" try: tree = self.get_subtree(tree, 'fundingtree')[0] except IndexError: # pragma: nocover pass funder_node = self.get_subtree(tree, 'funder') subfunder_node = self.get_subtree(tree, '//funding_level_0') funder_id = self.get_text_node(...
= Resolver( pid_type='frdoi', object_type='rec', getter=Record.get_record) try: dummy_pid, funder_rec = resolver.resolve(funder_doi) funder_name = funder_rec['acronyms'][0] except PersistentIdentifierError: raise OAIRELoadingError( "Please ensure that funders have been loaded prior to" "loading grants. Could not resolv...
def grantxml2json(self, grant_xml): """Convert OpenAIRE grant XML into JSON.""" tree = etree.fromstring(grant_xml) # XML harvested from OAI-PMH has a different format/structure if tree.prefix == 'oai': ptree = self.get_subtree( tree, '/oai:record/oai:metadata/oaf:entity/oaf:project')[0] header = self.get_subtree(tree, ...
'enddate': enddate, 'funder': {'$ref': funder['url']}, 'program': funder['program'], 'url': url, 'remote_modified': modified, } return ret_json
def iter_grants(self, as_json=True): """Fetch records from the SQLite database.""" self._connect() result = self.db_connection.cursor().execute( "SELECT data, format FROM grants" ) for data, data_format in result: if (not as_json) and data_format == 'json': raise Exception("Cannot convert JSON source to XML output.") e...
def iter_grants(self, as_json=True): """Fetch grants from a remote OAI-PMH endpoint. Return the Sickle-provided generator object. """ records = self.client.ListRecords(metadataPrefix='oaf', set=self.setspec) for rec in records: try: grant_out = rec.raw # rec.raw is XML if as_json: grant_out = self.grantxml2json(grant_o...
def dump(self, as_json=True, commit_batch_size=100): """ Dump the grant information to a local storage. :param as_json: Convert XML to JSON before saving (default: True). """ connection = sqlite3.connect(self.destination) format_ = 'json' if as_json else 'xml' if not self._db_exists(connection): connection.execute( "CR...
def get_attrib(self, et_node, prefixed_attrib): """Get a prefixed attribute like 'rdf:resource' from ET node.""" prefix, attrib = prefixed_attrib.split(':') return et_node.get('{{{0}}}{1}'.format(self.namespaces[prefix], attrib))
def fundrefxml2json(self, node): """Convert a FundRef 'skos:Concept' node into JSON.""" doi = FundRefDOIResolver.strip_doi_host(self.get_attrib(node, 'rdf:about')) oaf_id = FundRefDOIResolver().resolve_by_doi( "http://dx.doi.org/" + doi) name = node.find('./skosxl:prefLabel/skosxl:Label/skosxl:literalForm', namespaces=...
parent, 'country': country_code, 'type': type_, 'subtype': subtype.lower(), 'remote_created': (created_elem.text if created_elem is not None else None), 'remote_modified': (modified_elem.text if modified_elem is not None else None), } return json_dict
def iter_funders(self): """Get a converted list of Funders as JSON dict.""" root = self.doc_root funders = root.findall('./skos:Concept', namespaces=self.namespaces) for funder in funders: funder_json = self.fundrefxml2json(funder) yield funder_json
def resolve_by_oai_id(self, oai_id): """Resolve the funder from the OpenAIRE OAI record id. Hack for when funder is not provided in OpenAIRE. """ if oai_id.startswith('oai:dnet:'): oai_id = oai_id[len('oai:dnet:'):] prefix = oai_id.split("::")[0] suffix = prefix.replace("_", "").upper() oaf = "{0}::{1}".format(prefix, ...
def split_resource_path(resource): """Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. """ pieces = [] for piece in resource.split('/'): if path.sep in piece \ or (path.altsep and path.altsep in piece) or \ piece == path.pardir: raise Resour...
def predicates(graph): """ Return a listing of all known predicates in the registered schemata, including the schema path they associate with, their name and allowed types. """ seen = set() def _traverse(binding): if binding.path in seen: return seen.add(binding.path) if binding.is_object: for prop in binding.propertie...
def passwordReset1to2(old): """ Power down and delete the item """ new = old.upgradeVersion(old.typeName, 1, 2, installedOn=None) for iface in new.store.interfacesFor(new): new.store.powerDown(new, iface) new.deleteFromStore()
def upgradeUserInfo1to2(oldUserInfo): """ Concatenate the I{firstName} and I{lastName} attributes from the old user info item and set the result as the I{realName} attribute of the upgraded item. """ newUserInfo = oldUserInfo.upgradeVersion( UserInfo.typeName, 1, 2, realName=oldUserInfo.firstName + u" " + oldUserInfo.l...
def ticket1to2(old): """ change Ticket to refer to Products and not benefactor factories. """ if isinstance(old.benefactor, Multifactor): types = list(chain(*[b.powerupNames for b in old.benefactor.benefactors('ascending')])) elif isinstance(old.benefactor, InitializerBenefactor): #oh man what a mess types = list(chain...
def _getPublicSignupInfo(siteStore): """ Get information about public web-based signup mechanisms. @param siteStore: a store with some signups installed on it (as indicated by _SignupTracker instances). @return: a generator which yields 2-tuples of (prompt, url) where 'prompt' is unicode briefly describing the signup m...
None: yield (p, u'/'+u)
def locateChild(self, ctx, segments): """ Initialize self with the given key's L{_PasswordResetAttempt}, if any. @param segments: a L{_PasswordResetAttempt} key (hopefully) @return: C{(self, ())} with C{self.attempt} initialized, or L{NotFound} @see: L{attemptByKey} """ if len(segments) == 1: attempt = self.attemptByKe...
def renderHTTP(self, ctx): """ Handle the password reset form. The following exchange describes the process: S: Render C{reset} C: POST C{username} or C{email} S: L{handleRequestForUser}, render C{reset-check-email} (User follows the emailed reset link) S: Render C{reset-step-two} C: POST C{password1} S: L{resetPasswor...
def handleRequestForUser(self, username, url): """ User C{username} wants to reset their password. Create an attempt item, and send them an email if the username is valid """ attempt = self.newAttemptForUser(username) account = self.accountByAddress(username) if account is None: # do we want to disclose this to the use...
def sendEmail(self, url, attempt, email, _sendEmail=_sendEmail): """ Send an email for the given L{_PasswordResetAttempt}. @type url: L{URL} @param url: The URL of the password reset page. @type attempt: L{_PasswordResetAttempt} @param attempt: An L{Item} representing a particular user's attempt to reset their password...
def attemptByKey(self, key): """ Locate the L{_PasswordResetAttempt} that corresponds to C{key} """ return self.store.findUnique(_PasswordResetAttempt, _PasswordResetAttempt.key == key, default=None)
def _makeKey(self, usern): """ Make a new, probably unique key. This key will be sent in an email to the user and is used to access the password change form. """ return unicode(hashlib.md5(str((usern, time.time(), random.random()))).hexdigest())
def newAttemptForUser(self, user): """ Create an L{_PasswordResetAttempt} for the user whose username is C{user} @param user: C{unicode} username """ # we could query for other attempts by the same # user within some timeframe and raise an exception, # if we wanted return _PasswordResetAttempt(store=self.store, usernam...
def resetPassword(self, attempt, newPassword): """ @param attempt: L{_PasswordResetAttempt} reset the password of the user who initiated C{attempt} to C{newPassword}, and afterward, delete the attempt and any persistent sessions that belong to the user """ self.accountByAddress(attempt.username).password = newPassword ...
def issueViaEmail(self, issuer, email, product, templateData, domainName, httpPort=80): """ Send a ticket via email to the supplied address, which, when claimed, will create an avatar and allow the given product to endow it with things. @param issuer: An object, preferably a user, to track who issued this ticket. @para...
%(from)s: To be used for the From: header; will contain an rfc2822-format address. %(to)s: the address that we are going to send to. %(date)s: an rfc2822-format date. %(message-id)s: an rfc2822 message-id %(link)s: an HTTP URL that we are generating a link to. """ ticket = self.createTicket(issuer, unicode(email, 'asci...
def usernameAvailable(self, username, domain): """ Check to see if a username is available for the user to select. """ if len(username) < 2: return [False, u"Username too short"] for char in u"[ ,:;<>@()!\"'%&\\|\t\b": if char in username: return [False, u"Username contains invalid character: '%s'" % char] # The localp...
def createUser(self, realName, username, domain, password, emailAddress): """ Create a user, storing some associated metadata in the user's store, i.e. their first and last names (as a L{UserInfo} item), and a L{axiom.userbase.LoginMethod} allowing them to login with their email address. @param realName: the real name ...
be called in a transaction, it shouldn't # start a transaction itself. def _(): loginsystem = self.store.findUnique(userbase.LoginSystem) # Create an account with the credentials they specified, # making it internal since it belongs to us. acct = loginsystem.addAccount(username, domain, password, verified=True, interna...
def createSignup(self, creator, signupClass, signupConf, product, emailTemplate, prompt): """ Create a new signup facility in the site store's database. @param creator: a unicode string describing the creator of the new signup mechanism, for auditing purposes. @param signupClass: the item type of the signup mechanism t...
= siteStore.findOrCreate(TicketBooth, lambda booth: installOn(booth, siteStore)) signupItem = signupClass( store=siteStore, booth=booth, product=product, emailTemplate=emailTemplate, prompt=prompt, **signupConf) siteStore.powerUp(signupItem) _SignupTracker(store=siteStore, signupItem=signupItem, createdOn=extime.Time()...
def makeProductPicker(self): """ Make a LiveForm with radio buttons for each Product in the store. """ productPicker = liveform.LiveForm( self.coerceProduct, [liveform.Parameter( str(id(product)), liveform.FORM_INPUT, liveform.LiveForm( lambda selectedProduct, product=product: selectedProduct and product, [liveform.Par...
def _deleteTrackers(self, trackers): """ Delete the given signup trackers and their associated signup resources. @param trackers: sequence of L{_SignupTrackers} """ for tracker in trackers: if tracker.store is None: # we're not updating the list of live signups client side, so # we might get a signup that has already b...
def fetch(self): """ Fetch & return a new `Image` object representing the image's current state :rtype: Image :raises DOAPIError: if the API endpoint replies with an error (e.g., if the image no longer exists) """ api = self.doapi_manager return api._image(api.request(self.url)["image"])
def update_image(self, name): # The `_image` is to avoid conflicts with MutableMapping.update. """ Update (i.e., rename) the image :param str name: the new name for the image :return: an updated `Image` object :rtype: Image :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager retur...
def generate(self, nameformat=None, capitalize=None, formatters=None, **kwargs): '''Pick a random name form a specified list of name parts''' nameformat = nameformat or self.nameformat capitalize = capitalize or self.capitalize formatters = formatters or {} lines = self._get_lines(kwargs) names = dict((k, v['name']) fo...
def pick_frequency_line(self, filename, frequency, cumulativefield='cumulative_frequency'): '''Given a numeric frequency, pick a line from a csv with a cumulative frequency field''' if resource_exists('censusname', filename): with closing(resource_stream('censusname', filename)) as b: g = codecs.iterdecode(b, 'ascii') ...
def dfl_local_dir(): """ Infers a default local directory, which is DFL_DIR_PARENT/<project name>, where the project name is guessed according to the following rules. If we detect we're in a repository, the project name is the repository name (git only for now). If we're not in a repository, and the script file sys.arg...
def git_repo(): """ Returns the git repository root if the cwd is in a repo, else None """ try: reldir = subprocess.check_output( ["git", "rev-parse", "--git-dir"]) reldir = reldir.decode("utf-8") return os.path.basename(os.path.dirname(os.path.abspath(reldir))) except subprocess.CalledProcessError: return None
def git_hash(): """returns the current git hash or unknown if not in git repo""" if git_repo() is None: return "unknown" git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"]) # git_hash is a byte string; we want a string. git_hash = git_hash.decode("utf-8") # git_hash also comes with an extra \n at the end,...
def git_pretty(): """returns a pretty summary of the commit or unkown if not in git repo""" if git_repo() is None: return "unknown" pretty = subprocess.check_output( ["git", "log", "--pretty=format:%h %s", "-n", "1"]) pretty = pretty.decode("utf-8") pretty = pretty.strip() return pretty
def invocation(): """reconstructs the invocation for this python program""" cmdargs = [sys.executable] + sys.argv[:] invocation = " ".join(shlex.quote(s) for s in cmdargs) return invocation
def serialize(func): """ Falcon response serialization """ def wrapped(instance, req, resp, **kwargs): assert not req.get_param("unicode") or req.get_param("unicode") == u"✓", "Unicode sanity check failed" resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate"); resp.set_header("Pragma", "no-cache"); re...
def readRow(self, row, startCol=0, endCol=-1): ''' read row ''' return self.__operation.readRow(row, startCol, endCol)
def readCol(self, col, startRow=0, endRow=-1): ''' read col ''' return self.__operation.readCol(col, startRow, endRow)
def writeCell(self, row, col, value): ''' write cell''' self.__operation.writeCell(row, col, value)
def openSheet(self, name): ''' set a sheet to write ''' if name not in self.__sheetNameDict: sheet = self.__workbook.add_sheet(name) self.__sheetNameDict[name] = sheet self.__sheet = self.__sheetNameDict[name]
def __getSheet(self, name): ''' get a sheet by name ''' if not self.sheetExsit(name): raise UfException(Errors.SHEET_NAME_INVALID, "Can't find a sheet named %s" % name) return self.__sheetNameDict[name]
def writeCell(self, row, col, value): ''' write a cell ''' if self.__sheet is None: self.openSheet(super(ExcelWrite, self).DEFAULT_SHEET) self.__sheet.write(row, col, value)
def writeRow(self, row, values): ''' write a row Not sure whether xlwt support write the same cell multiple times ''' if self.__sheet is None: self.openSheet(super(ExcelWrite, self).DEFAULT_SHEET) for index, value in enumerate(values): self.__sheet.write(row, index, value)
def readCell(self, row, col): ''' read a cell''' try: if self.__sheet is None: self.openSheet(super(ExcelRead, self).DEFAULT_SHEET) return self.__sheet.cell(row, col).value except BaseException as excp: raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in Excellib.readCell %s" % excp)
def delete_url(self, url): """ Delete local files downloaded from given URL """ # file may exist locally in compressed and decompressed states # delete both for decompress in [False, True]: key = (url, decompress) if key in self._local_paths: path = self._local_paths[key] remove(path) del self._local_paths[key] # possi...
def exists(self, url, filename=None, decompress=False): """ Return True if a local file corresponding to these arguments exists. """ return download.file_exists( url, filename=filename, decompress=decompress, subdir=self.subdir)
def fetch( self, url, filename=None, decompress=False, force=False, timeout=None, use_wget_if_available=True): """ Return the local path to the downloaded copy of a given URL. Don't download the file again if it's already present, unless `force` is True. """ key = (url, decompress) if not force and key in self._local_p...
def local_filename( self, url=None, filename=None, decompress=False): """ What local filename will we use within the cache directory for the given URL/filename/decompress options. """ return common.build_local_filename(url, filename, decompress)
def local_path(self, url, filename=None, decompress=False, download=False): """ What will the full local path be if we download the given file? """ if download: return self.fetch(url=url, filename=filename, decompress=decompress) else: filename = self.local_filename(url, filename, decompress) return join(self.cache_dir...
def connect_redis(redis_client, name=None, transaction=False): """ Connect your redis-py instance to redpipe. Example: .. code:: python redpipe.connect_redis(redis.StrictRedis(), name='users') Do this during your application bootstrapping. You can also pass a redis-py-cluster instance to this method. .. code:: python r...
def connect(cls, pipeline_method, name=None): """ Low level logic to bind a callable method to a name. Don't call this directly unless you know what you are doing. :param pipeline_method: callable :param name: str optional :return: None """ new_pool = pipeline_method().connection_pool try: if cls.get(name).connection_p...
def connect_redis(cls, redis_client, name=None, transaction=False): """ Store the redis connection in our connector instance. Do this during your application bootstrapping. We call the pipeline method of the redis client. The ``redis_client`` can be either a redis or rediscluster client. We use the interface, not the a...
always use the MULTI/EXEC flags, but I don't see much point. If you need transactional support I recommend using a LUA script. **RedPipe** is about improving network round-trip efficiency. :param redis_client: redis.StrictRedis() or redis.Redis() :param name: identifier for the connection, optional :param transaction: ...
def remoteIndexer1to2(oldIndexer): """ Previously external application code was responsible for adding a RemoteListener to a batch work source as a reliable listener. This precluded the possibility of the RemoteListener resetting itself unilaterally. With version 2, RemoteListener takes control of adding itself as a re...
def remoteIndexer2to3(oldIndexer): """ The documentType keyword was added to all indexable items. Indexes need to be regenerated for this to take effect. Also, PyLucene no longer stores the text of messages it indexes, so deleting and re-creating the indexes will make them much smaller. """ newIndexer = oldIndexer.upgr...
def pyLuceneIndexer4to5(old): """ Copy attributes, reset index due because information about deleted documents has been lost, and power up for IFulltextIndexer so other code can find this item. """ new = old.upgradeVersion(PyLuceneIndexer.typeName, 4, 5, indexCount=old.indexCount, installedOn=old.installedOn, indexDire...
def addSource(self, itemSource): """ Add the given L{IBatchProcessor} as a source of input for this indexer. """ _IndexerInputSource(store=self.store, indexer=self, source=itemSource) itemSource.addReliableListener(self, style=iaxiom.REMOTE)
def reset(self): """ Process everything all over again. """ self.indexCount = 0 indexDir = self.store.newDirectory(self.indexDirectory) if indexDir.exists(): indexDir.remove() for src in self.getSources(): src.removeReliableListener(self) src.addReliableListener(self, style=iaxiom.REMOTE)
def _flush(self): """ Deal with pending result-affecting things. This should always be called before issuing a search. """ remove = self.store.query(_RemoveDocument) documentIdentifiers = list(remove.getColumn("documentIdentifier")) if VERBOSE: log.msg("%s/%d removing %r" % (self.store, self.storeID, documentIdentifier...
def reset(self): """ In addition to the behavior of the superclass, delete any dangling lockfiles which may prevent this index from being opened. With the tested version of PyLucene (something pre-2.0), this appears to not actually be necessary: deleting the entire index directory but leaving the lockfile in place seem...
def add(self, document): """ Add a document to the database. """ docid = int(document.uniqueIdentifier()) text = u' '.join(document.textParts()) self.store.executeSQL(self.addSQL, (docid, text))
def remove(self, docid): """ Remove a document from the database. """ docid = int(docid) self.store.executeSQL(self.removeSQL, (docid,))
def search(self, term, keywords=None, sortAscending=True): """ Search the database. """ if sortAscending: direction = 'ASC' else: direction = 'DESC' return [_SQLiteResultWrapper(r[0]) for r in self.store.querySQL(self.searchSQL % (direction,), (term,))]
def _getStore(self): """ Get the Store used for FTS. If it does not exist, it is created and initialised. """ storeDir = self.store.newDirectory(self.indexDirectory) if not storeDir.exists(): store = Store(storeDir) self._initStore(store) return store else: return Store(storeDir)
def init(track_log_handler): """ (Re)initialize track's file handler for track package logger. Adds a stdout-printing handler automatically. """ logger = logging.getLogger(__package__) # TODO (just document prominently) # assume only one trial can run at once right now # multi-concurrent-trial support will require comp...
def debug(s, *args): """debug(s, x1, ..., xn) logs s.format(x1, ..., xn).""" # Get the path name and line number of the function which called us. previous_frame = inspect.currentframe().f_back try: pathname, lineno, _, _, _ = inspect.getframeinfo(previous_frame) # if path is in cwd, simplify it cwd = os.path.abspath(os...
def dump(self, value): """Dumps the value to string. :returns: Returns the stringified version of the value. :raises: TypeError, ValueError """ value = self.__convert__(value) self.__validate__(value) return self.__serialize__(value)
def simulate(self): """Generates a random integer in the available range.""" min_ = (-sys.maxsize - 1) if self._min is None else self._min max_ = sys.maxsize if self._max is None else self._max return random.randint(min_, max_)
def simulate(self): """Returns a randomly constructed string. Simulate randomly constructs a string with a length between min and max. If min is not present, a minimum length of 1 is assumed, if max is not present a maximum length of 10 is used. """ min_ = 1 if self._min is None else self._min max_ = 10 if self._max is...
def simulate(self): """Simulates a stream of types.""" # Simulates zero to 10 types return [t.simulate() for t in itertools.islice(self, random.choice(range(10)))]
def __findRange(self, excelLib, start, end): ''' return low and high as excel range ''' inc = 1 low = 0 high = 0 dates = excelLib.readCol(0, 1) for index, date in enumerate(dates): if int(start) <= int(date): low = index + inc break if low: for index, date in reversed(list(enumerate(dates))): if int(date) <= int(end): ...
def __readData(self, targetPath, start, end): ''' read data ''' ret = [] if not path.exists(targetPath): LOG.error("Target file doesn't exist: %s" % path.abspath(targetPath) ) return ret with ExcelLib(fileName = targetPath, mode = ExcelLib.READ_MODE) as excel: low, high = self.__findRange(excel, start, end) for index i...
def __writeData(self, targetPath, fields, rows): ''' write data ''' if path.exists(targetPath): LOG.error("Target file exists: %s" % path.abspath(targetPath) ) raise UfException(Errors.FILE_EXIST, "can't write to a existing file") #because xlwt doesn't support it with ExcelLib(fileName = targetPath, mode = ExcelLib.WRI...
def readQuotes(self, start, end): ''' read quotes ''' quotes = self.__readData(self.targetPath(ExcelDAM.QUOTE), start, end) return [Quote(*quote) for quote in quotes]
def writeQuotes(self, quotes): ''' write quotes ''' self.__writeData(self.targetPath(ExcelDAM.QUOTE), QUOTE_FIELDS, [[getattr(quote, field) for field in QUOTE_FIELDS] for quote in quotes])
def readTicks(self, start, end): ''' read ticks ''' ticks = self.__readData(self.targetPath(ExcelDAM.TICK), start, end) return [Tick(*tick) for tick in ticks]
def writeTicks(self, ticks): ''' read quotes ''' self.__writeData(self.targetPath(ExcelDAM.TICK), TICK_FIELDS, [[getattr(tick, field) for field in TICK_FIELDS] for tick in ticks])
def snap(self, *args): """Records multiple values at once. It takes two to six arguments specifying which values should be recorded together. Valid arguments are 'x', 'y', 'r', 'theta', 'aux1', 'aux2', 'aux3', 'aux4', 'frequency', 'trace1', 'trace2', 'trace3' and 'trace4'. snap is faster since it avoids communication o...
= Enum( 'x', 'y', 'r', 'theta', 'aux1', 'aux2', 'aux3', 'aux4', 'frequency', 'trace1', 'trace2', 'trace3', 'trace4' ) # construct command, cmd = 'SNAP?', (Float,) * length, (param, ) * length return self._ask(cmd, *args)
def save(self, mode='all'): """Saves to the file specified by :attr:`~SR850.filename`. :param mode: Defines what to save. ======= ================================================ Value Description ======= ================================================ 'all' Saves the active display's data trace, the trace definition ...
def recall(self, mode='all'): """Recalls from the file specified by :attr:`~SR850.filename`. :param mode: Specifies the recall mode. ======= ================================================== Value Description ======= ================================================== 'all' Recalls the active display's data trace, the ...
def fit(self, range, function=None): """Fits a function to the active display's data trace within a specified range of the time window. E.g.:: # Fit's a gaussian to the first 30% of the time window. lockin.fit(range=(0, 30), function='gauss') :param start: The left limit of the time window in percent. :param stop: The ...
is not stored when the fit command is executed. """ if function is not None: self.fit_function = function cmd = 'FITT', Integer(min=0, max=100), Integer(min=0, max=100) self._write(cmd, start, stop)
def calculate_statistics(self, start, stop): """Starts the statistics calculation. :param start: The left limit of the time window in percent. :param stop: The right limit of the time window in percent. .. note:: The calculation takes some time. Check the status byte to see when the operation is done. A running scan wi...
def calculate(self, operation=None, trace=None, constant=None, type=None): """Starts the calculation. The calculation operates on the trace graphed in the active display. The math operation is defined by the :attr:`~.SR850.math_operation`, the second argument by the :attr:`~.SR850.math_argument_type`. For convenience, ...