sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def run(self): ''' Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory ''' qry = os.path.abspath(self.qry) ref = os.path.abspath(self.ref) outfile = os.path.abspath(self.outf...
Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory
entailment
def update_indel(self, nucmer_snp): '''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False''' new_v...
Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False
entailment
def reader(fname): '''Helper function to open the results file (coords file) and create alignment objects with the values in it''' f = pyfastaq.utils.open_file_read(fname) for line in f: if line.startswith('[') or (not '\t' in line): continue yield alignment.Alignment(line) ...
Helper function to open the results file (coords file) and create alignment objects with the values in it
entailment
def convert_to_msp_crunch(infile, outfile, ref_fai=None, qry_fai=None): '''Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely). ACT ignores sequence names in the crunch file, and just looks at the numbers. To make a compatible file, the coords all must be shifted appro...
Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely). ACT ignores sequence names in the crunch file, and just looks at the numbers. To make a compatible file, the coords all must be shifted appropriately, which can be done by providing both the ref_fai and qry_fai op...
entailment
def _request(self, method, url, params=None, headers=None, data=None): """Common handler for all the HTTP requests.""" if not params: params = {} # set default headers if not headers: headers = { 'accept': '*/*' } if method...
Common handler for all the HTTP requests.
entailment
def user_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a user profile. Defaults to linking to Github profiles, but the profile URIS can be configured via the ``issues_user_uri`` config value. Examples: :: :user:`sloria` Anchor text a...
Sphinx role for linking to a user profile. Defaults to linking to Github profiles, but the profile URIS can be configured via the ``issues_user_uri`` config value. Examples: :: :user:`sloria` Anchor text also works: :: :user:`Steven Loria <sloria>`
entailment
def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a CVE on https://cve.mitre.org. Examples: :: :cve:`CVE-2018-17175` """ options = options or {} content = content or [] has_explicit_title, title, target = split_explicit_title...
Sphinx role for linking to a CVE on https://cve.mitre.org. Examples: :: :cve:`CVE-2018-17175`
entailment
def list_line(self, line): """ Write the given iterable of values (line) to the file as items on the same line. Any argument that stringifies to a string legal as a TSV data item can be written. Does not copy the line or build a big string in memory. """ ...
Write the given iterable of values (line) to the file as items on the same line. Any argument that stringifies to a string legal as a TSV data item can be written. Does not copy the line or build a big string in memory.
entailment
def prepare(doc): """ Parse metadata to obtain list of mustache templates, then load those templates. """ doc.mustache_files = doc.get_metadata('mustache') if isinstance(doc.mustache_files, basestring): # process single YAML value stored as string if not doc.mustache_files: ...
Parse metadata to obtain list of mustache templates, then load those templates.
entailment
def action(elem, doc): """ Apply combined mustache template to all strings in document. """ if type(elem) == Str and doc.mhash is not None: elem.text = doc.mrenderer.render(elem.text, doc.mhash) return elem
Apply combined mustache template to all strings in document.
entailment
def get_callback(self, renderer_context): """ Determine the name of the callback to wrap around the json output. """ request = renderer_context.get('request', None) params = request and get_query_params(request) or {} return params.get(self.callback_parameter, self.defaul...
Determine the name of the callback to wrap around the json output.
entailment
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders into jsonp, wrapping the json output in a callback function. Clients may set the callback function name using a query parameter on the URL, for example: ?callback=exampleCallbackName """ ...
Renders into jsonp, wrapping the json output in a callback function. Clients may set the callback function name using a query parameter on the URL, for example: ?callback=exampleCallbackName
entailment
def get(self, measurementId): """ Analyses the measurement with the given parameters :param measurementId: :return: """ logger.info('Loading raw data for ' + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.C...
Analyses the measurement with the given parameters :param measurementId: :return:
entailment
def to_jd(year, week, day): '''Return Julian day count of given ISO year, week, and day''' return day + n_weeks(SUN, gregorian.to_jd(year - 1, 12, 28), week)
Return Julian day count of given ISO year, week, and day
entailment
def from_jd(jd): '''Return tuple of ISO (year, week, day) for Julian day''' year = gregorian.from_jd(jd)[0] day = jwday(jd) + 1 dayofyear = ordinal.from_jd(jd)[1] week = trunc((dayofyear - day + 10) / 7) # Reset year if week < 1: week = weeks_per_year(year - 1) year = year ...
Return tuple of ISO (year, week, day) for Julian day
entailment
def weeks_per_year(year): '''Number of ISO weeks in a year''' # 53 weeks: any year starting on Thursday and any leap year starting on Wednesday jan1 = jwday(gregorian.to_jd(year, 1, 1)) if jan1 == THU or (jan1 == WED and isleap(year)): return 53 else: return 52
Number of ISO weeks in a year
entailment
def stsci(hdulist): """For STScI GEIS files, need to do extra steps.""" instrument = hdulist[0].header.get('INSTRUME', '') # Update extension header keywords if instrument in ("WFPC2", "FOC"): rootname = hdulist[0].header.get('ROOTNAME', '') filetype = hdulist[0].header.get('FILETYPE',...
For STScI GEIS files, need to do extra steps.
entailment
def stsci2(hdulist, filename): """For STScI GEIS files, need to do extra steps.""" # Write output file name to the primary header instrument = hdulist[0].header.get('INSTRUME', '') if instrument in ("WFPC2", "FOC"): hdulist[0].header['FILENAME'] = filename
For STScI GEIS files, need to do extra steps.
entailment
def readgeis(input): """Input GEIS files "input" will be read and a HDUList object will be returned. The user can use the writeto method to write the HDUList object to a FITS file. """ global dat cardLen = fits.Card.length # input file(s) must be of the form *.??h and *.??d ...
Input GEIS files "input" will be read and a HDUList object will be returned. The user can use the writeto method to write the HDUList object to a FITS file.
entailment
def parse_path(f1, f2): """Parse two input arguments and return two lists of file names""" import glob # if second argument is missing or is a wild card, point it # to the current directory f2 = f2.strip() if f2 == '' or f2 == '*': f2 = './' # if the first argument is a directory...
Parse two input arguments and return two lists of file names
entailment
def parseinput(inputlist,outputname=None, atfile=None): """ Recursively parse user input based upon the irafglob program and construct a list of files that need to be processed. This program addresses the following deficiencies of the irafglob program:: parseinput can extract filenames from asso...
Recursively parse user input based upon the irafglob program and construct a list of files that need to be processed. This program addresses the following deficiencies of the irafglob program:: parseinput can extract filenames from association tables Returns ------- This program will return...
entailment
def checkASN(filename): """ Determine if the filename provided to the function belongs to an association. Parameters ---------- filename: string Returns ------- validASN : boolean value """ # Extract the file extn type: extnType = filename[filename.rfind('_')+1:filena...
Determine if the filename provided to the function belongs to an association. Parameters ---------- filename: string Returns ------- validASN : boolean value
entailment
def countinputs(inputlist): """ Determine the number of inputfiles provided by the user and the number of those files that are association tables Parameters ---------- inputlist : string the user input Returns ------- numInputs: int number of inputs provided by th...
Determine the number of inputfiles provided by the user and the number of those files that are association tables Parameters ---------- inputlist : string the user input Returns ------- numInputs: int number of inputs provided by the user numASNfiles: int numb...
entailment
def summary(logfile, time_format): "show a summary of all projects" def output(summary): width = max([len(p[0]) for p in summary]) + 3 print '\n'.join([ "%s%s%s" % (p[0], ' ' * (width - len(p[0])), colored(minutes_to_txt(p[1]), 'red')) for p in summary]) output(server.summarize(read(logfil...
show a summary of all projects
entailment
def status(logfile, time_format): "show current status" try: r = read(logfile, time_format)[-1] if r[1][1]: return summary(logfile, time_format) else: print "working on %s" % colored(r[0], attrs=['bold']) print " since %s" % colored( server.date_to_txt(r[1][0], time_format...
show current status
entailment
def start(project, logfile, time_format): "start tracking for <project>" records = read(logfile, time_format) if records and not records[-1][1][1]: print "error: there is a project already active" return write(server.start(project, records), logfile, time_format) print "starting work on %s" % color...
start tracking for <project>
entailment
def stop(logfile, time_format): "stop tracking for the active project" def save_and_output(records): records = server.stop(records) write(records, logfile, time_format) def output(r): print "worked on %s" % colored(r[0], attrs=['bold']) print " from %s" % colored( server.date_t...
stop tracking for the active project
entailment
def parse(logfile, time_format): "parses a stream with text formatted as a Timed logfile and shows a summary" records = [server.record_from_txt(line, only_elapsed=True, time_format=time_format) for line in sys.stdin.readlines()] # TODO: make this code better. def output(summary): width = max([len(p[0]...
parses a stream with text formatted as a Timed logfile and shows a summary
entailment
def projects(logfile, time_format): "prints a newline-separated list of all projects" print '\n'.join(server.list_projects(read(logfile, time_format)))
prints a newline-separated list of all projects
entailment
def getLTime(): """Returns a formatted string with the current local time.""" _ltime = _time.localtime(_time.time()) tlm_str = _time.strftime('%H:%M:%S (%d/%m/%Y)', _ltime) return tlm_str
Returns a formatted string with the current local time.
entailment
def getDate(): """Returns a formatted string with the current date.""" _ltime = _time.localtime(_time.time()) date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime) return date_str
Returns a formatted string with the current date.
entailment
def convertDate(date): """Convert DATE string into a decimal year.""" d, t = date.split('T') return decimal_date(d, timeobs=t)
Convert DATE string into a decimal year.
entailment
def decimal_date(dateobs, timeobs=None): """Convert DATE-OBS (and optional TIME-OBS) into a decimal year.""" year, month, day = dateobs.split('-') if timeobs is not None: hr, min, sec = timeobs.split(':') else: hr, min, sec = 0, 0, 0 rdate = datetime.datetime(int(year), int(month),...
Convert DATE-OBS (and optional TIME-OBS) into a decimal year.
entailment
def interpretDQvalue(input): """ Converts an integer 'input' into its component bit values as a list of power of 2 integers. For example, the bit value 1027 would return [1, 2, 1024] """ nbits = 16 # We will only support integer values up to 2**128 for iexp in [16, 32, 64, 128]: ...
Converts an integer 'input' into its component bit values as a list of power of 2 integers. For example, the bit value 1027 would return [1, 2, 1024]
entailment
def isFits(input): """ Returns -------- isFits: tuple An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and ``fitstype`` are specified as: - ``isfits``: True|False - ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None Notes ----- ...
Returns -------- isFits: tuple An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and ``fitstype`` are specified as: - ``isfits``: True|False - ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None Notes ----- Input images which do not ha...
entailment
def verifyWriteMode(files): """ Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be writable, it will print out...
Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be writable, it will print out the list of names of affected files.
entailment
def getFilterNames(header, filternames=None): """ Returns a comma-separated string of filter names extracted from the input header (PyFITS header object). This function has been hard-coded to support the following instruments: ACS, WFPC2, STIS This function relies on the 'INSTRUME' keywor...
Returns a comma-separated string of filter names extracted from the input header (PyFITS header object). This function has been hard-coded to support the following instruments: ACS, WFPC2, STIS This function relies on the 'INSTRUME' keyword to define what instrument has been used to generate ...
entailment
def buildNewRootname(filename, extn=None, extlist=None): """ Build rootname for a new file. Use 'extn' for new filename if given, does NOT append a suffix/extension at all. Does NOT check to see if it exists already. Will ALWAYS return a new filename. """ # Search known suffixes to r...
Build rootname for a new file. Use 'extn' for new filename if given, does NOT append a suffix/extension at all. Does NOT check to see if it exists already. Will ALWAYS return a new filename.
entailment
def buildRootname(filename, ext=None): """ Build a new rootname for an existing file and given extension. Any user supplied extensions to use for searching for file need to be provided as a list of extensions. Examples -------- :: >>> rootname = buildRootname(filename, ext=['_dth...
Build a new rootname for an existing file and given extension. Any user supplied extensions to use for searching for file need to be provided as a list of extensions. Examples -------- :: >>> rootname = buildRootname(filename, ext=['_dth.fits']) # doctest: +SKIP
entailment
def getKeyword(filename, keyword, default=None, handle=None): """ General, write-safe method for returning a keyword value from the header of a IRAF recognized image. Returns the value as a string. """ # Insure that there is at least 1 extension specified... if filename.find('[') < 0: ...
General, write-safe method for returning a keyword value from the header of a IRAF recognized image. Returns the value as a string.
entailment
def getHeader(filename, handle=None): """ Return a copy of the PRIMARY header, along with any group/extension header for this filename specification. """ _fname, _extn = parseFilename(filename) # Allow the user to provide an already opened PyFITS object # to derive the header from... # ...
Return a copy of the PRIMARY header, along with any group/extension header for this filename specification.
entailment
def updateKeyword(filename, key, value,show=yes): """Add/update keyword to header with given value.""" _fname, _extn = parseFilename(filename) # Open image whether it is FITS or GEIS _fimg = openImage(_fname, mode='update') # Address the correct header _hdr = getExtn(_fimg, _extn).header ...
Add/update keyword to header with given value.
entailment
def buildFITSName(geisname): """Build a new FITS filename for a GEIS input image.""" # User wants to make a FITS copy and update it... _indx = geisname.rfind('.') _fitsname = geisname[:_indx] + '_' + geisname[_indx + 1:-1] + 'h.fits' return _fitsname
Build a new FITS filename for a GEIS input image.
entailment
def openImage(filename, mode='readonly', memmap=False, writefits=True, clobber=True, fitsname=None): """ Opens file and returns PyFITS object. Works on both FITS and GEIS formatted images. Notes ----- If a GEIS or waivered FITS image is used as input, it will convert it to a ...
Opens file and returns PyFITS object. Works on both FITS and GEIS formatted images. Notes ----- If a GEIS or waivered FITS image is used as input, it will convert it to a MEF object and only if ``writefits = True`` will write it out to a file. If ``fitsname = None``, the name used to write out...
entailment
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. """ # Parse out any extension specified in filename _indx = filename.find('[') if _indx > 0: # Read extension name provided _fname = fil...
Parse out filename from any specified extensions. Returns rootname and string version of extension name.
entailment
def parseExtn(extn=None): """ Parse a string representing a qualified fits extension name as in the output of `parseFilename` and return a tuple ``(str(extname), int(extver))``, which can be passed to `astropy.io.fits` functions using the 'ext' kw. Default return is the first extension in a fit...
Parse a string representing a qualified fits extension name as in the output of `parseFilename` and return a tuple ``(str(extname), int(extver))``, which can be passed to `astropy.io.fits` functions using the 'ext' kw. Default return is the first extension in a fits file. Examples -------- ...
entailment
def countExtn(fimg, extname='SCI'): """ Return the number of 'extname' extensions, defaulting to counting the number of SCI extensions. """ closefits = False if isinstance(fimg, string_types): fimg = fits.open(fimg) closefits = True n = 0 for e in fimg: if 'extn...
Return the number of 'extname' extensions, defaulting to counting the number of SCI extensions.
entailment
def getExtn(fimg, extn=None): """ Returns the PyFITS extension corresponding to extension specified in filename. Defaults to returning the first extension with data or the primary extension, if none have data. If a non-existent extension has been specified, it raises a `KeyError` exception. ...
Returns the PyFITS extension corresponding to extension specified in filename. Defaults to returning the first extension with data or the primary extension, if none have data. If a non-existent extension has been specified, it raises a `KeyError` exception.
entailment
def findFile(input): """Search a directory for full filename with optional path.""" # If no input name is provided, default to returning 'no'(FALSE) if not input: return no # We use 'osfn' here to insure that any IRAF variables are # expanded out before splitting out the path... _fdir,...
Search a directory for full filename with optional path.
entailment
def checkFileExists(filename, directory=None): """ Checks to see if file specified exists in current or specified directory. Default is current directory. Returns 1 if it exists, 0 if not found. """ if directory is not None: fname = os.path.join(directory,filename) else: fname...
Checks to see if file specified exists in current or specified directory. Default is current directory. Returns 1 if it exists, 0 if not found.
entailment
def copyFile(input, output, replace=None): """Copy a file whole from input to output.""" _found = findFile(output) if not _found or (_found and replace): shutil.copy2(input, output)
Copy a file whole from input to output.
entailment
def removeFile(inlist): """ Utility function for deleting a list of files or a single file. This function will automatically delete both files of a GEIS image, just like 'iraf.imdelete'. """ if not isinstance(inlist, string_types): # We do have a list, so delete all filenames in list. ...
Utility function for deleting a list of files or a single file. This function will automatically delete both files of a GEIS image, just like 'iraf.imdelete'.
entailment
def findKeywordExtn(ft, keyword, value=None): """ This function will return the index of the extension in a multi-extension FITS file which contains the desired keyword with the given value. """ i = 0 extnum = -1 # Search through all the extensions in the FITS object for chip in ft: ...
This function will return the index of the extension in a multi-extension FITS file which contains the desired keyword with the given value.
entailment
def findExtname(fimg, extname, extver=None): """ Returns the list number of the extension corresponding to EXTNAME given. """ i = 0 extnum = None for chip in fimg: hdr = chip.header if 'EXTNAME' in hdr: if hdr['EXTNAME'].strip() == extname.upper(): if...
Returns the list number of the extension corresponding to EXTNAME given.
entailment
def rAsciiLine(ifile): """Returns the next non-blank line in an ASCII file.""" _line = ifile.readline().strip() while len(_line) == 0: _line = ifile.readline().strip() return _line
Returns the next non-blank line in an ASCII file.
entailment
def listVars(prefix="", equals="\t= ", **kw): """List IRAF variables.""" keylist = getVarList() if len(keylist) == 0: print('No IRAF variables defined') else: keylist.sort() for word in keylist: print("%s%s%s%s" % (prefix, word, equals, envget(word)))
List IRAF variables.
entailment
def untranslateName(s): """Undo Python conversion of CL parameter or variable name.""" s = s.replace('DOT', '.') s = s.replace('DOLLAR', '$') # delete 'PY' at start of name components if s[:2] == 'PY': s = s[2:] s = s.replace('.PY', '.') return s
Undo Python conversion of CL parameter or variable name.
entailment
def envget(var, default=None): """Get value of IRAF or OS environment variable.""" if 'pyraf' in sys.modules: #ONLY if pyraf is already loaded, import iraf into the namespace from pyraf import iraf else: # else set iraf to None so it knows to not use iraf's environment iraf ...
Get value of IRAF or OS environment variable.
entailment
def osfn(filename): """Convert IRAF virtual path name to OS pathname.""" # Try to emulate the CL version closely: # # - expands IRAF virtual file names # - strips blanks around path components # - if no slashes or relative paths, return relative pathname # - otherwise return absolute pathna...
Convert IRAF virtual path name to OS pathname.
entailment
def defvar(varname): """Returns true if CL variable is defined.""" if 'pyraf' in sys.modules: #ONLY if pyraf is already loaded, import iraf into the namespace from pyraf import iraf else: # else set iraf to None so it knows to not use iraf's environment iraf = None if i...
Returns true if CL variable is defined.
entailment
def set(*args, **kw): """Set IRAF environment variables.""" if len(args) == 0: if len(kw) != 0: # normal case is only keyword,value pairs for keyword, value in kw.items(): keyword = untranslateName(keyword) svalue = str(value) _var...
Set IRAF environment variables.
entailment
def show(*args, **kw): """Print value of IRAF or OS environment variables.""" if len(kw): raise TypeError('unexpected keyword argument: %r' % list(kw)) if args: for arg in args: print(envget(arg)) else: # print them all listVars(prefix=" ", equals="=")
Print value of IRAF or OS environment variables.
entailment
def unset(*args, **kw): """ Unset IRAF environment variables. This is not a standard IRAF task, but it is obviously useful. It makes the resulting variables undefined. It silently ignores variables that are not defined. It does not change the os environment variables. """ if len(kw) != ...
Unset IRAF environment variables. This is not a standard IRAF task, but it is obviously useful. It makes the resulting variables undefined. It silently ignores variables that are not defined. It does not change the os environment variables.
entailment
def Expand(instring, noerror=0): """ Expand a string with embedded IRAF variables (IRAF virtual filename). Allows comma-separated lists. Also uses os.path.expanduser to replace '~' symbols. Set the noerror flag to silently replace undefined variables with just the variable name or null (so Ex...
Expand a string with embedded IRAF variables (IRAF virtual filename). Allows comma-separated lists. Also uses os.path.expanduser to replace '~' symbols. Set the noerror flag to silently replace undefined variables with just the variable name or null (so Expand('abc$def') = 'abcdef' and Expand('(a...
entailment
def _expand1(instring, noerror): """Expand a string with embedded IRAF variables (IRAF virtual filename).""" # first expand names in parentheses # note this works on nested names too, expanding from the # inside out (just like IRAF) mm = __re_var_paren.search(instring) while mm is not None: ...
Expand a string with embedded IRAF variables (IRAF virtual filename).
entailment
def legal_date(year, month, day): '''Check if this is a legal date in the Julian calendar''' daysinmonth = month_length(year, month) if not (0 < day <= daysinmonth): raise ValueError("Month {} doesn't have a day {}".format(month, day)) return True
Check if this is a legal date in the Julian calendar
entailment
def from_jd(jd): '''Calculate Julian calendar date from Julian day''' jd += 0.5 z = trunc(jd) a = z b = a + 1524 c = trunc((b - 122.1) / 365.25) d = trunc(365.25 * c) e = trunc((b - d) / 30.6001) if trunc(e < 14): month = e - 1 else: month = e - 13 if trun...
Calculate Julian calendar date from Julian day
entailment
def to_jd(year, month, day): '''Convert to Julian day using astronomical years (0 = 1 BC, -1 = 2 BC)''' legal_date(year, month, day) # Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page 61 if month <= 2: year -= 1 month += 12 return (trunc((365.25 * (year + 471...
Convert to Julian day using astronomical years (0 = 1 BC, -1 = 2 BC)
entailment
def delay_1(year): '''Test for delay of start of new year and to avoid''' # Sunday, Wednesday, and Friday as start of the new year. months = trunc(((235 * year) - 234) / 19) parts = 12084 + (13753 * months) day = trunc((months * 29) + parts / 25920) if ((3 * (day + 1)) % 7) < 3: day += ...
Test for delay of start of new year and to avoid
entailment
def delay_2(year): '''Check for delay in start of new year due to length of adjacent years''' last = delay_1(year - 1) present = delay_1(year) next_ = delay_1(year + 1) if next_ - present == 356: return 2 elif present - last == 382: return 1 else: return 0
Check for delay in start of new year due to length of adjacent years
entailment
def month_days(year, month): '''How many days are in a given month of a given year''' if month > 13: raise ValueError("Incorrect month index") # First of all, dispose of fixed-length 29 day months if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR): return 29 # If it's not a leap yea...
How many days are in a given month of a given year
entailment
def byteswap(input,output=None,clobber=True): """Input GEIS files "input" will be read and converted to a new GEIS file whose byte-order has been swapped from its original state. Parameters ---------- input - str Full filename with path of input GEIS image header file output - str ...
Input GEIS files "input" will be read and converted to a new GEIS file whose byte-order has been swapped from its original state. Parameters ---------- input - str Full filename with path of input GEIS image header file output - str Full filename with path of output GEIS image head...
entailment
def start(self, measurementId, durationInSeconds=None): """ Initialises the device if required then enters a read loop taking data from the provider and passing it to the handler. It will continue until either breakRead is true or the duration (if provided) has passed. :return: ...
Initialises the device if required then enters a read loop taking data from the provider and passing it to the handler. It will continue until either breakRead is true or the duration (if provided) has passed. :return:
entailment
def get(self, targetId): """ Yields the analysed wav data. :param targetId: :return: """ result = self._targetController.analyse(targetId) if result: if len(result) == 2: if result[1] == 404: return result ...
Yields the analysed wav data. :param targetId: :return:
entailment
def put(self, targetId): """ stores a new target. :param targetId: the target to store. :return: """ json = request.get_json() if 'hinge' in json: logger.info('Storing target ' + targetId) if self._targetController.storeFromHinge(targetId, ...
stores a new target. :param targetId: the target to store. :return:
entailment
def to_datetime(jdc): '''Return a datetime for the input floating point Julian Day Count''' year, month, day = gregorian.from_jd(jdc) # in jdc: 0.0 = noon, 0.5 = midnight # the 0.5 changes it to 0.0 = midnight, 0.5 = noon frac = (jdc + 0.5) % 1 hours = int(24 * frac) mfrac = frac * 24 - h...
Return a datetime for the input floating point Julian Day Count
entailment
def dict_from_qs(qs): ''' Slightly introverted parser for lists of dot-notation nested fields i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}} ''' entries = qs.split(',') if qs.strip() else [] entries = [entry.strip() for entry in entries] def _dict_from_qs(line, d): ...
Slightly introverted parser for lists of dot-notation nested fields i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}}
entailment
def qs_from_dict(qsdict, prefix=""): ''' Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr" ''' prefix = prefix + '.' if prefix else "" def descend(qsd): for key, val in sorted(qsd.items()): if val: yield qs_...
Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr"
entailment
def dbcon(func): """Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created.""" @wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.dbcon is None: # set up connection self.dbco...
Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created.
entailment
def add(self, sid, token): """ Add new sensor to the database Parameters ---------- sid : str SensorId token : str """ try: self.dbcur.execute(SQL_SENSOR_INS, (sid, token)) except sqlite3.IntegrityError: # sensor entry exi...
Add new sensor to the database Parameters ---------- sid : str SensorId token : str
entailment
def remove(self, sid): """ Remove sensor from the database Parameters ---------- sid : str SensorID """ self.dbcur.execute(SQL_SENSOR_DEL, (sid,)) self.dbcur.execute(SQL_TMPO_DEL, (sid,))
Remove sensor from the database Parameters ---------- sid : str SensorID
entailment
def sync(self, *sids): """ Synchronise data Parameters ---------- sids : list of str SensorIDs to sync Optional, leave empty to sync everything """ if sids == (): sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)] ...
Synchronise data Parameters ---------- sids : list of str SensorIDs to sync Optional, leave empty to sync everything
entailment
def list(self, *sids): """ List all tmpo-blocks in the database Parameters ---------- sids : list of str SensorID's for which to list blocks Optional, leave empty to get them all Returns ------- list[list[tuple]] """ ...
List all tmpo-blocks in the database Parameters ---------- sids : list of str SensorID's for which to list blocks Optional, leave empty to get them all Returns ------- list[list[tuple]]
entailment
def series(self, sid, recycle_id=None, head=None, tail=None, datetime=True): """ Create data Series Parameters ---------- sid : str recycle_id : optional head : int | pandas.Timestamp, optional Start of the interval default ...
Create data Series Parameters ---------- sid : str recycle_id : optional head : int | pandas.Timestamp, optional Start of the interval default earliest available tail : int | pandas.Timestamp, optional End of the interval d...
entailment
def dataframe(self, sids, head=0, tail=EPOCHS_MAX, datetime=True): """ Create data frame Parameters ---------- sids : list[str] head : int | pandas.Timestamp, optional Start of the interval default earliest available tail : int | pandas.Ti...
Create data frame Parameters ---------- sids : list[str] head : int | pandas.Timestamp, optional Start of the interval default earliest available tail : int | pandas.Timestamp, optional End of the interval default max epoch ...
entailment
def first_timestamp(self, sid, epoch=False): """ Get the first available timestamp for a sensor Parameters ---------- sid : str SensorID epoch : bool default False If True return as epoch If False return as pd.Timestamp ...
Get the first available timestamp for a sensor Parameters ---------- sid : str SensorID epoch : bool default False If True return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int
entailment
def last_timestamp(self, sid, epoch=False): """ Get the theoretical last timestamp for a sensor Parameters ---------- sid : str SensorID epoch : bool default False If True return as epoch If False return as pd.Timestamp ...
Get the theoretical last timestamp for a sensor Parameters ---------- sid : str SensorID epoch : bool default False If True return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int
entailment
def last_datapoint(self, sid, epoch=False): """ Parameters ---------- sid : str SensorId epoch : bool default False If True return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int,...
Parameters ---------- sid : str SensorId epoch : bool default False If True return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int, float
entailment
def _npdelta(self, a, delta): """Numpy: Modifying Array Values http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html""" for x in np.nditer(a, op_flags=["readwrite"]): delta += x x[...] = delta return a
Numpy: Modifying Array Values http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html
entailment
def sigStrToKwArgsDict(checkFuncSig): """ Take a check function signature (string), and parse it to get a dict of the keyword args and their values. """ p1 = checkFuncSig.find('(') p2 = checkFuncSig.rfind(')') assert p1 > 0 and p2 > 0 and p2 > p1, "Invalid signature: "+checkFuncSig argParts ...
Take a check function signature (string), and parse it to get a dict of the keyword args and their values.
entailment
def separateKeywords(kwArgsDict): """ Look through the keywords passed and separate the special ones we have added from the legal/standard ones. Return both sets as two dicts (in a tuple), as (standardKws, ourKws) """ standardKws = {} ourKws = {} for k in kwArgsDict: if k in STA...
Look through the keywords passed and separate the special ones we have added from the legal/standard ones. Return both sets as two dicts (in a tuple), as (standardKws, ourKws)
entailment
def addKwdArgsToSig(sigStr, kwArgsDict): """ Alter the passed function signature string to add the given kewords """ retval = sigStr if len(kwArgsDict) > 0: retval = retval.strip(' ,)') # open up the r.h.s. for more args for k in kwArgsDict: if retval[-1] != '(': retval += ", " ...
Alter the passed function signature string to add the given kewords
entailment
def _gauss_funct(p, fjac=None, x=None, y=None, err=None, weights=None): """ Defines the gaussian function to be used as the model. """ if p[2] != 0.0: Z = (x - p[1]) / p[2] model = p[0] * np.e ** (-Z ** 2 / 2.0) else: model = np.zeros(np.size(x)) statu...
Defines the gaussian function to be used as the model.
entailment
def gfit1d(y, x=None, err=None, weights=None, par=None, parinfo=None, maxiter=200, quiet=0): """ Return the gaussian fit as an object. Parameters ---------- y: 1D Numpy array The data to be fitted x: 1D Numpy array (optional) The x values of the y array. x and y m...
Return the gaussian fit as an object. Parameters ---------- y: 1D Numpy array The data to be fitted x: 1D Numpy array (optional) The x values of the y array. x and y must have the same shape. err: 1D Numpy array (optional) 1D array with measurement errors, must b...
entailment
def filter(self, *args, **kwargs): """filter lets django managers use `objects.filter` on a hashable object.""" obj = kwargs.pop(self.object_property_name, None) if obj is not None: kwargs['object_hash'] = self.model._compute_hash(obj) return super().filter(*args, **kwargs)
filter lets django managers use `objects.filter` on a hashable object.
entailment
def _extract_model_params(self, defaults, **kwargs): """this method allows django managers use `objects.get_or_create` and `objects.update_or_create` on a hashable object. """ obj = kwargs.pop(self.object_property_name, None) if obj is not None: kwargs['object_hash'] ...
this method allows django managers use `objects.get_or_create` and `objects.update_or_create` on a hashable object.
entailment
def persist(self): """a private method that persists an estimator object to the filesystem""" if self.object_hash: data = dill.dumps(self.object_property) f = ContentFile(data) self.object_file.save(self.object_hash, f, save=False) f.close() se...
a private method that persists an estimator object to the filesystem
entailment
def load(self): """a private method that loads an estimator object from the filesystem""" if self.is_file_persisted: self.object_file.open() temp = dill.loads(self.object_file.read()) self.set_object(temp) self.object_file.close()
a private method that loads an estimator object from the filesystem
entailment
def create_from_file(cls, filename): """Return an Estimator object given the path of the file, relative to the MEDIA_ROOT""" obj = cls() obj.object_file = filename obj.load() return obj
Return an Estimator object given the path of the file, relative to the MEDIA_ROOT
entailment
def getAppDir(): """ Return our application dir. Create it if it doesn't exist. """ # Be sure the resource dir exists theDir = os.path.expanduser('~/.')+APP_NAME.lower() if not os.path.exists(theDir): try: os.mkdir(theDir) except OSError: print('Could not create ...
Return our application dir. Create it if it doesn't exist.
entailment