Search is not available for this dataset
text stringlengths 75 104k |
|---|
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... |
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... |
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)
... |
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... |
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... |
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... |
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... |
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.
"""
... |
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:
... |
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 |
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... |
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
"""
... |
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... |
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) |
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 ... |
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 |
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',... |
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 |
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
... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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]... |
def projects(logfile, time_format):
"prints a newline-separated list of all projects"
print '\n'.join(server.list_projects(read(logfile, time_format))) |
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 |
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 |
def convertDate(date):
"""Convert DATE string into a decimal year."""
d, t = date.split('T')
return decimal_date(d, timeobs=t) |
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),... |
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]:
... |
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
-----
... |
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... |
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... |
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... |
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... |
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:
... |
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...
#
... |
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
... |
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 |
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
... |
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... |
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... |
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... |
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.
... |
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,... |
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... |
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) |
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.
... |
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:
... |
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... |
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 |
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))) |
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 |
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 ... |
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... |
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... |
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... |
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="=") |
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) != ... |
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... |
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:
... |
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 |
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... |
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... |
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 += ... |
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 |
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... |
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
... |
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:
... |
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
... |
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, ... |
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... |
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):
... |
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_... |
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... |
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... |
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,)) |
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)]
... |
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]]
"""
... |
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 ... |
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... |
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
... |
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
... |
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,... |
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 |
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 ... |
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... |
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 += ", "
... |
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... |
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... |
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) |
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'] ... |
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... |
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() |
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 |
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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.