sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def get(self, key, failobj=None, exact=0): """Raises exception if key is ambiguous""" if not exact: key = self.getfullkey(key,new=1) return self.data.get(key,failobj)
Raises exception if key is ambiguous
entailment
def _has(self, key, exact=0): """Raises an exception if key is ambiguous""" if not exact: key = self.getfullkey(key,new=1) return key in self.data
Raises an exception if key is ambiguous
entailment
def getall(self, key, failobj=None): """Returns a list of all the matching values for key, containing a single entry for unambiguous matches and multiple entries for ambiguous matches.""" if self.mmkeys is None: self._mmInit() k = self.mmkeys.get(key) if not k: return fai...
Returns a list of all the matching values for key, containing a single entry for unambiguous matches and multiple entries for ambiguous matches.
entailment
def getallkeys(self, key, failobj=None): """Returns a list of the full key names (not the items) for all the matching values for key. The list will contain a single entry for unambiguous matches and multiple entries for ambiguous matches.""" if self.mmkeys is None: self._mmInit(...
Returns a list of the full key names (not the items) for all the matching values for key. The list will contain a single entry for unambiguous matches and multiple entries for ambiguous matches.
entailment
def get(self, key, failobj=None, exact=0): """Returns failobj if key is not found or is ambiguous""" if not exact: try: key = self.getfullkey(key) except KeyError: return failobj return self.data.get(key,failobj)
Returns failobj if key is not found or is ambiguous
entailment
def _has(self, key, exact=0): """Returns false if key is not found or is ambiguous""" if not exact: try: key = self.getfullkey(key) return 1 except KeyError: return 0 else: return key in self.data
Returns false if key is not found or is ambiguous
entailment
def parFactory(fields, strict=0): """parameter factory function fields is a list of the comma-separated fields (as in the .par file). Each entry is a string or None (indicating that field was omitted.) Set the strict parameter to a non-zero value to do stricter parsing (to find errors in the inpu...
parameter factory function fields is a list of the comma-separated fields (as in the .par file). Each entry is a string or None (indicating that field was omitted.) Set the strict parameter to a non-zero value to do stricter parsing (to find errors in the input)
entailment
def setCmdline(self,value=1): """Set cmdline flag""" # set through dictionary to avoid extra calls to __setattr__ if value: self.__dict__['flags'] = self.flags | _cmdlineFlag else: self.__dict__['flags'] = self.flags & ~_cmdlineFlag
Set cmdline flag
entailment
def setChanged(self,value=1): """Set changed flag""" # set through dictionary to avoid another call to __setattr__ if value: self.__dict__['flags'] = self.flags | _changedFlag else: self.__dict__['flags'] = self.flags & ~_changedFlag
Set changed flag
entailment
def isLearned(self, mode=None): """Return true if this parameter is learned Hidden parameters are not learned; automatic parameters inherit behavior from package/cl; other parameters are learned. If mode is set, it determines how automatic parameters behave. If not set, cl.mode ...
Return true if this parameter is learned Hidden parameters are not learned; automatic parameters inherit behavior from package/cl; other parameters are learned. If mode is set, it determines how automatic parameters behave. If not set, cl.mode parameter determines behavior.
entailment
def getWithPrompt(self): """Interactively prompt for parameter value""" if self.prompt: pstring = self.prompt.split("\n")[0].strip() else: pstring = self.name if self.choice: schoice = list(map(self.toString, self.choice)) pstring = pstring...
Interactively prompt for parameter value
entailment
def get(self, field=None, index=None, lpar=0, prompt=1, native=0, mode="h"): """Return value of this parameter as a string (or in native format if native is non-zero.)""" if field and field != "p_value": # note p_value comes back to this routine, so shortcut that case re...
Return value of this parameter as a string (or in native format if native is non-zero.)
entailment
def set(self, value, field=None, index=None, check=1): """Set value of this parameter from a string or other value. Field is optional parameter field (p_prompt, p_minimum, etc.) Index is optional array index (zero-based). Set check=0 to assign the value without checking to see if it is ...
Set value of this parameter from a string or other value. Field is optional parameter field (p_prompt, p_minimum, etc.) Index is optional array index (zero-based). Set check=0 to assign the value without checking to see if it is within the min-max range or in the choice list.
entailment
def checkValue(self,value,strict=0): """Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.) """ v = self._coerceValue(value,strict) return self.chec...
Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.)
entailment
def checkOneValue(self,v,strict=0): """Checks a single value to see if it is in range or choice list Allows indirection strings starting with ")". Assumes v has already been converted to right value by _coerceOneValue. Returns value if OK, or raises ValueError if not OK. ...
Checks a single value to see if it is in range or choice list Allows indirection strings starting with ")". Assumes v has already been converted to right value by _coerceOneValue. Returns value if OK, or raises ValueError if not OK.
entailment
def dpar(self, cl=1): """Return dpar-style executable assignment for parameter Default is to write CL version of code; if cl parameter is false, writes Python executable code instead. """ sval = self.toString(self.value, quoted=1) if not cl: if sval == "": sv...
Return dpar-style executable assignment for parameter Default is to write CL version of code; if cl parameter is false, writes Python executable code instead.
entailment
def pretty(self,verbose=0): """Return pretty list description of parameter""" # split prompt lines and add blanks in later lines to align them plines = self.prompt.split('\n') for i in range(len(plines)-1): plines[i+1] = 32*' ' + plines[i+1] plines = '\n'.join(plines) nam...
Return pretty list description of parameter
entailment
def save(self, dolist=0): """Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file. """ quoted = not dolist fields = 7*[""] fields[0] = self.name...
Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file.
entailment
def _setChoice(self,s,strict=0): """Set choice parameter from string s""" clist = _getChoice(s,strict) self.choice = list(map(self._coerceValue, clist)) self._setChoiceDict()
Set choice parameter from string s
entailment
def _setChoiceDict(self): """Create dictionary for choice list""" # value is name of choice parameter (same as key) self.choiceDict = {} for c in self.choice: self.choiceDict[c] = c
Create dictionary for choice list
entailment
def _optionalPrompt(self, mode): """Interactively prompt for parameter if necessary Prompt for value if (1) mode is hidden but value is undefined or bad, or (2) mode is query and value was not set on command line Never prompt for "u" mode parameters, which are local variables. ...
Interactively prompt for parameter if necessary Prompt for value if (1) mode is hidden but value is undefined or bad, or (2) mode is query and value was not set on command line Never prompt for "u" mode parameters, which are local variables.
entailment
def _getPFilename(self,native,prompt): """Get p_filename field for this parameter Same as get for non-list params """ return self.get(native=native,prompt=prompt)
Get p_filename field for this parameter Same as get for non-list params
entailment
def _getField(self, field, native=0, prompt=1): """Get a parameter field value""" try: # expand field name using minimum match field = _getFieldDict[field] except KeyError as e: # re-raise the exception with a bit more info raise SyntaxError("Canno...
Get a parameter field value
entailment
def _setField(self, value, field, check=1): """Set a parameter field value""" try: # expand field name using minimum match field = _setFieldDict[field] except KeyError as e: raise SyntaxError("Cannot set field " + field + " for parameter " ...
Set a parameter field value
entailment
def save(self, dolist=0): """Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file. """ quoted = not dolist array_size = 1 for d in self.shape: ...
Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file.
entailment
def dpar(self, cl=1): """Return dpar-style executable assignment for parameter Default is to write CL version of code; if cl parameter is false, writes Python executable code instead. Note that dpar doesn't even work for arrays in the CL, so we just use Python syntax here. ...
Return dpar-style executable assignment for parameter Default is to write CL version of code; if cl parameter is false, writes Python executable code instead. Note that dpar doesn't even work for arrays in the CL, so we just use Python syntax here.
entailment
def get(self, field=None, index=None, lpar=0, prompt=1, native=0, mode="h"): """Return value of this parameter as a string (or in native format if native is non-zero.)""" if field: return self._getField(field,native=native,prompt=prompt) # may prompt for value if prompt flag is set ...
Return value of this parameter as a string (or in native format if native is non-zero.)
entailment
def set(self, value, field=None, index=None, check=1): """Set value of this parameter from a string or other value. Field is optional parameter field (p_prompt, p_minimum, etc.) Index is optional array index (zero-based). Set check=0 to assign the value without checking to see if it is ...
Set value of this parameter from a string or other value. Field is optional parameter field (p_prompt, p_minimum, etc.) Index is optional array index (zero-based). Set check=0 to assign the value without checking to see if it is within the min-max range or in the choice list.
entailment
def checkValue(self,value,strict=0): """Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.) """ v = self._coerceValue(value,strict) for i in range(l...
Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.)
entailment
def _sumindex(self, index=None): """Convert tuple index to 1-D index into value""" try: ndim = len(index) except TypeError: # turn index into a 1-tuple index = (index,) ndim = 1 if len(self.shape) != ndim: raise ValueError("Inde...
Convert tuple index to 1-D index into value
entailment
def _coerceValue(self,value,strict=0): """Coerce parameter to appropriate type Should accept None or null string. Must be an array. """ try: if isinstance(value,str): # allow single blank-separated string as input value = value.split() ...
Coerce parameter to appropriate type Should accept None or null string. Must be an array.
entailment
def _setChoiceDict(self): """Create min-match dictionary for choice list""" # value is full name of choice parameter self.choiceDict = minmatch.MinMatchDict() for c in self.choice: self.choiceDict.add(c, c)
Create min-match dictionary for choice list
entailment
def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.min: warning("Minimum value not allowed for boolean-type parameter " + self.name, strict) self.min = None if self.max: if not self.prompt: ...
Check initial attributes to make sure they are legal
entailment
def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.choice: warning("Choice values not allowed for real-type parameter " + self.name, strict) self.choice = None
Check initial attributes to make sure they are legal
entailment
def patch(self, deviceId): """ Updates the device with the given data. Supports a json payload like { fs: newFs samplesPerBatch: samplesPerBatch gyroEnabled: true gyroSensitivity: 500 accelerometerEnabled: true accelerometer...
Updates the device with the given data. Supports a json payload like { fs: newFs samplesPerBatch: samplesPerBatch gyroEnabled: true gyroSensitivity: 500 accelerometerEnabled: true accelerometerSensitivity: 2 } A heartbeat is...
entailment
def legal_date(year, month, day): '''Check if this is a legal date in the Gregorian calendar''' if month == 2: daysinmonth = 29 if isleap(year) else 28 else: daysinmonth = 30 if month in HAVE_30_DAYS else 31 if not (0 < day <= daysinmonth): raise ValueError("Month {} doesn't hav...
Check if this is a legal date in the Gregorian calendar
entailment
def to_jd2(year, month, day): '''Gregorian to Julian Day Count for years between 1801-2099''' # http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html legal_date(year, month, day) if month <= 2: year = year - 1 month = month + 12 a = floor(year / 100) b = floor(a / 4) c = ...
Gregorian to Julian Day Count for years between 1801-2099
entailment
def from_jd(jd): '''Return Gregorian date in a (Y, M, D) tuple''' wjd = floor(jd - 0.5) + 0.5 depoch = wjd - EPOCH quadricent = floor(depoch / INTERCALATION_CYCLE_DAYS) dqc = depoch % INTERCALATION_CYCLE_DAYS cent = floor(dqc / LEAP_SUPPRESSION_DAYS) dcent = dqc % LEAP_SUPPRESSION_DAYS ...
Return Gregorian date in a (Y, M, D) tuple
entailment
def storeFromHinge(self, name, hingePoints): """ Stores a new item in the cache if it is allowed in. :param name: the name. :param hingePoints: the hinge points. :return: true if it is stored. """ if name not in self._cache: if self._valid(hingePoints...
Stores a new item in the cache if it is allowed in. :param name: the name. :param hingePoints: the hinge points. :return: true if it is stored.
entailment
def storeFromWav(self, uploadCacheEntry, start, end): """ Stores a new item in the cache. :param name: file name. :param start: start time. :param end: end time. :return: true if stored. """ prefix = uploadCacheEntry['name'] + '_' + start + '_' + end ...
Stores a new item in the cache. :param name: file name. :param start: start time. :param end: end time. :return: true if stored.
entailment
def delete(self, name): """ Deletes the named entry in the cache. :param name: the name. :return: true if it is deleted. """ if name in self._cache: del self._cache[name] self.writeCache() # TODO clean files return True ...
Deletes the named entry in the cache. :param name: the name. :return: true if it is deleted.
entailment
def analyse(self, name): """ reads the specified file. :param name: the name. :return: the analysis as frequency/Pxx. """ if name in self._cache: target = self._cache[name] if target['type'] == 'wav': signal = self._uploadController...
reads the specified file. :param name: the name. :return: the analysis as frequency/Pxx.
entailment
def log_interp1d(self, xx, yy, kind='linear'): """ Performs a log space 1d interpolation. :param xx: the x values. :param yy: the y values. :param kind: the type of interpolation to apply (as per scipy interp1d) :return: the interpolation function. """ log...
Performs a log space 1d interpolation. :param xx: the x values. :param yy: the y values. :param kind: the type of interpolation to apply (as per scipy interp1d) :return: the interpolation function.
entailment
def to_jd(year, month, day): "Retrieve the Julian date equivalent for this date" return day + (month - 1) * 30 + (year - 1) * 365 + floor(year / 4) + EPOCH - 1
Retrieve the Julian date equivalent for this date
entailment
def from_jd(jdc): "Create a new date from a Julian date." cdc = floor(jdc) + 0.5 - EPOCH year = floor((cdc - floor((cdc + 366) / 1461)) / 365) + 1 yday = jdc - to_jd(year, 1, 1) month = floor(yday / 30) + 1 day = yday - (month - 1) * 30 + 1 return year, month, day
Create a new date from a Julian date.
entailment
def troll(roll, dec, v2, v3): """ Computes the roll angle at the target position based on:: the roll angle at the V1 axis(roll), the dec of the target(dec), and the V2/V3 position of the aperture (v2,v3) in arcseconds. Based on the algorithm provided by Colin Cox that i...
Computes the roll angle at the target position based on:: the roll angle at the V1 axis(roll), the dec of the target(dec), and the V2/V3 position of the aperture (v2,v3) in arcseconds. Based on the algorithm provided by Colin Cox that is used in Generic Conversion a...
entailment
def print_archive(self,format=True): """ Prints out archived WCS keywords.""" if len(list(self.orig_wcs.keys())) > 0: block = 'Original WCS keywords for ' + self.rootname+ '\n' block += ' backed up on '+repr(self.orig_wcs['WCSCDATE'])+'\n' if not format: ...
Prints out archived WCS keywords.
entailment
def set_pscale(self): """ Compute the pixel scale based on active WCS values. """ if self.new: self.pscale = 1.0 else: self.pscale = self.compute_pscale(self.cd11,self.cd21)
Compute the pixel scale based on active WCS values.
entailment
def compute_pscale(self,cd11,cd21): """ Compute the pixel scale based on active WCS values. """ return N.sqrt(N.power(cd11,2)+N.power(cd21,2)) * 3600.
Compute the pixel scale based on active WCS values.
entailment
def set_orient(self): """ Return the computed orientation based on CD matrix. """ self.orient = RADTODEG(N.arctan2(self.cd12,self.cd22))
Return the computed orientation based on CD matrix.
entailment
def updateWCS(self, pixel_scale=None, orient=None,refpos=None,refval=None,size=None): """ Create a new CD Matrix from the absolute pixel scale and reference image orientation. """ # Set up parameters necessary for updating WCS # Check to see if new value is provided, ...
Create a new CD Matrix from the absolute pixel scale and reference image orientation.
entailment
def scale_WCS(self,pixel_scale,retain=True): ''' Scale the WCS to a new pixel_scale. The 'retain' parameter [default value: True] controls whether or not to retain the original distortion solution in the CD matrix. ''' _ratio = pixel_scale / self.pscale # Correct the siz...
Scale the WCS to a new pixel_scale. The 'retain' parameter [default value: True] controls whether or not to retain the original distortion solution in the CD matrix.
entailment
def xy2rd(self,pos): """ This method would apply the WCS keywords to a position to generate a new sky position. The algorithm comes directly from 'imgtools.xy2rd' translate (x,y) to (ra, dec) """ if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0: ...
This method would apply the WCS keywords to a position to generate a new sky position. The algorithm comes directly from 'imgtools.xy2rd' translate (x,y) to (ra, dec)
entailment
def rd2xy(self,skypos,hour=no): """ This method would use the WCS keywords to compute the XY position from a given RA/Dec tuple (in deg). NOTE: Investigate how to let this function accept arrays as well as single positions. WJH 27Mar03 """ if self.ctype1.find('T...
This method would use the WCS keywords to compute the XY position from a given RA/Dec tuple (in deg). NOTE: Investigate how to let this function accept arrays as well as single positions. WJH 27Mar03
entailment
def rotateCD(self,orient): """ Rotates WCS CD matrix to new orientation given by 'orient' """ # Determine where member CRVAL position falls in ref frame # Find out whether this needs to be rotated to align with # reference frame. _delta = self.get_orient() - orient ...
Rotates WCS CD matrix to new orientation given by 'orient'
entailment
def write(self,fitsname=None,wcs=None,archive=True,overwrite=False,quiet=True): """ Write out the values of the WCS keywords to the specified image. If it is a GEIS image and 'fitsname' has been provided, it will automatically make a multi-extension FITS copy of the GEIS...
Write out the values of the WCS keywords to the specified image. If it is a GEIS image and 'fitsname' has been provided, it will automatically make a multi-extension FITS copy of the GEIS and update that file. Otherwise, it throw an Exception if the user attempts to directly upd...
entailment
def restore(self): """ Reset the active WCS keywords to values stored in the backup keywords. """ # If there are no backup keys, do nothing... if len(list(self.backup.keys())) == 0: return for key in self.backup.keys(): if key != 'WCSCDATE': ...
Reset the active WCS keywords to values stored in the backup keywords.
entailment
def archive(self,prepend=None,overwrite=no,quiet=yes): """ Create backup copies of the WCS keywords with the given prepended string. If backup keywords are already present, only update them if 'overwrite' is set to 'yes', otherwise, do warn the user and do nothing. ...
Create backup copies of the WCS keywords with the given prepended string. If backup keywords are already present, only update them if 'overwrite' is set to 'yes', otherwise, do warn the user and do nothing. Set the WCSDATE at this time as well.
entailment
def read_archive(self,header,prepend=None): """ Extract a copy of WCS keywords from an open file header, if they have already been created and remember the prefix used for those keywords. Otherwise, setup the current WCS keywords as the archive values. """ # S...
Extract a copy of WCS keywords from an open file header, if they have already been created and remember the prefix used for those keywords. Otherwise, setup the current WCS keywords as the archive values.
entailment
def write_archive(self,fitsname=None,overwrite=no,quiet=yes): """ Saves a copy of the WCS keywords from the image header as new keywords with the user-supplied 'prepend' character(s) prepended to the old keyword names. If the file is a GEIS image and 'fitsname' is not None, ...
Saves a copy of the WCS keywords from the image header as new keywords with the user-supplied 'prepend' character(s) prepended to the old keyword names. If the file is a GEIS image and 'fitsname' is not None, create a FITS copy and update that version; otherwise, raise ...
entailment
def restoreWCS(self,prepend=None): """ Resets the WCS values to the original values stored in the backup keywords recorded in self.backup. """ # Open header for image image = self.rootname if prepend: _prepend = prepend elif self.prepend: _prepend = self.prep...
Resets the WCS values to the original values stored in the backup keywords recorded in self.backup.
entailment
def createReferenceWCS(self,refname,overwrite=yes): """ Write out the values of the WCS keywords to the NEW specified image 'fitsname'. """ hdu = self.createWcsHDU() # If refname already exists, delete it to make way for new file if os.path.exists(refname): ...
Write out the values of the WCS keywords to the NEW specified image 'fitsname'.
entailment
def createWcsHDU(self): """ Generate a WCS header object that can be used to populate a reference WCS HDU. """ hdu = fits.ImageHDU() hdu.header['EXTNAME'] = 'WCS' hdu.header['EXTVER'] = 1 # Now, update original image size information hdu.header['WCSAXE...
Generate a WCS header object that can be used to populate a reference WCS HDU.
entailment
def main(args=None): """ The main routine. """ logger = cfg.configureLogger() for root, dirs, files in os.walk(cfg.dataDir): for dir in dirs: newDir = os.path.join(root, dir) try: os.removedirs(newDir) logger.info("Deleted empty dir " + str(new...
The main routine.
entailment
def leap(year, method=None): ''' Determine if this is a leap year in the FR calendar using one of three methods: 4, 100, 128 (every 4th years, every 4th or 400th but not 100th, every 4th but not 128th) ''' method = method or 'equinox' if year in (3, 7, 11): return True elif year < ...
Determine if this is a leap year in the FR calendar using one of three methods: 4, 100, 128 (every 4th years, every 4th or 400th but not 100th, every 4th but not 128th)
entailment
def premier_da_la_annee(jd): '''Determine the year in the French revolutionary calendar in which a given Julian day falls. Returns Julian day number containing fall equinox (first day of the FR year)''' p = ephem.previous_fall_equinox(dublin.from_jd(jd)) previous = trunc(dublin.to_jd(p) - 0.5) + 0.5 ...
Determine the year in the French revolutionary calendar in which a given Julian day falls. Returns Julian day number containing fall equinox (first day of the FR year)
entailment
def to_jd(year, month, day, method=None): '''Obtain Julian day from a given French Revolutionary calendar date.''' method = method or 'equinox' if day < 1 or day > 30: raise ValueError("Invalid day for this calendar") if month > 13: raise ValueError("Invalid month for this calendar") ...
Obtain Julian day from a given French Revolutionary calendar date.
entailment
def _to_jd_schematic(year, month, day, method): '''Calculate JD using various leap-year calculation methods''' y0, y1, y2, y3, y4, y5 = 0, 0, 0, 0, 0, 0 intercal_cycle_yrs, over_cycle_yrs, leap_suppression_yrs = None, None, None # Use the every-four-years method below year 16 (madler) or below 15 (ro...
Calculate JD using various leap-year calculation methods
entailment
def from_jd(jd, method=None): '''Calculate date in the French Revolutionary calendar from Julian day. The five or six "sansculottides" are considered a thirteenth month in the results of this function.''' method = method or 'equinox' if method == 'equinox': return _from_jd_equinox(jd) ...
Calculate date in the French Revolutionary calendar from Julian day. The five or six "sansculottides" are considered a thirteenth month in the results of this function.
entailment
def _from_jd_schematic(jd, method): '''Convert from JD using various leap-year calculation methods''' if jd < EPOCH: raise ValueError("Can't convert days before the French Revolution") # days since Epoch J = trunc(jd) + 0.5 - EPOCH y0, y1, y2, y3, y4, y5 = 0, 0, 0, 0, 0, 0 intercal_cyc...
Convert from JD using various leap-year calculation methods
entailment
def _from_jd_equinox(jd): '''Calculate the FR day using the equinox as day 1''' jd = trunc(jd) + 0.5 equinoxe = premier_da_la_annee(jd) an = gregorian.from_jd(equinoxe)[0] - YEAR_EPOCH mois = trunc((jd - equinoxe) / 30.) + 1 jour = int((jd - equinoxe) % 30) + 1 return (an, mois, jour)
Calculate the FR day using the equinox as day 1
entailment
def to_jd(year, month, day): '''Obtain Julian day for Indian Civil date''' gyear = year + 78 leap = isleap(gyear) # // Is this a leap year ? # 22 - leap = 21 if leap, 22 non-leap start = gregorian.to_jd(gyear, 3, 22 - leap) if leap: Caitra = 31 else: Caitra = 30 if...
Obtain Julian day for Indian Civil date
entailment
def from_jd(jd): '''Calculate Indian Civil date from Julian day Offset in years from Saka era to Gregorian epoch''' start = 80 # Day offset between Saka and Gregorian jd = trunc(jd) + 0.5 greg = gregorian.from_jd(jd) # Gregorian date for Julian day leap = isleap(greg[0]) # Is this a leap...
Calculate Indian Civil date from Julian day Offset in years from Saka era to Gregorian epoch
entailment
def format_stack(skip=0, length=6, _sep=os.path.sep): """ Returns a one-line string with the current callstack. """ return ' < '.join("%s:%s:%s" % ( '/'.join(f.f_code.co_filename.split(_sep)[-2:]), f.f_lineno, f.f_code.co_name ) for f in islice(frame_iterator(sys._getframe(1 ...
Returns a one-line string with the current callstack.
entailment
def log(func=None, stacktrace=10, stacktrace_align=60, attributes=(), module=True, call=True, call_args=True, call_args_repr=repr, result=True, exception=True, exception_repr=repr, result_repr=strip_non_ascii, use_logging='C...
Decorates `func` to have logging. Args func (function): Function to decorate. If missing log returns a partial which you can use as a decorator. stacktrace (int): Number of frames to show. stacktrace_align (int): Column to align the framelist to. ...
entailment
def wireHandlers(cfg): """ If the device is configured to run against a remote server, ping that device on a scheduled basis with our current state. :param cfg: the config object. :return: """ logger = logging.getLogger('recorder') httpPoster = cfg.handlers.get('remote') csvLogger = ...
If the device is configured to run against a remote server, ping that device on a scheduled basis with our current state. :param cfg: the config object. :return:
entailment
def main(args=None): """ The main routine. """ cfg.configureLogger() wireHandlers(cfg) # get config from a flask standard place not our config yml app.run(debug=cfg.runInDebug(), host='0.0.0.0', port=cfg.getPort())
The main routine.
entailment
def get(self, deviceId): """ lists all known active measurements. """ measurementsByName = self.measurements.get(deviceId) if measurementsByName is None: return [] else: return list(measurementsByName.values())
lists all known active measurements.
entailment
def get(self, deviceId, measurementId): """ details the specific measurement. """ record = self.measurements.get(deviceId) if record is not None: return record.get(measurementId) return None
details the specific measurement.
entailment
def put(self, deviceId, measurementId): """ Schedules a new measurement at the specified time. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if it was scheduled, 400 if the device is busy, 500 if the device is bad. ...
Schedules a new measurement at the specified time. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if it was scheduled, 400 if the device is busy, 500 if the device is bad.
entailment
def delete(self, deviceId, measurementId): """ Deletes a stored measurement. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if it was deleted, 400 if no such measurement (or device). """ record = self.measur...
Deletes a stored measurement. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if it was deleted, 400 if no such measurement (or device).
entailment
def get(self, deviceId, measurementId): """ signals a stop for the given measurement. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if stop is signalled, 400 if it doesn't exist or is not running. """ recor...
signals a stop for the given measurement. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if stop is signalled, 400 if it doesn't exist or is not running.
entailment
def schedule(self, duration, at=None, delay=None, callback=None): """ schedules the measurement (to execute asynchronously). :param duration: how long to run for. :param at: the time to start at. :param delay: the time to wait til starting (use at or delay). :param callba...
schedules the measurement (to execute asynchronously). :param duration: how long to run for. :param at: the time to start at. :param delay: the time to wait til starting (use at or delay). :param callback: a callback. :return: nothing.
entailment
def execute(self, duration): """ Executes the measurement, recording the event status. :param duration: the time to run for. :return: nothing. """ self.statuses.append({'name': ScheduledMeasurementStatus.RUNNING.name, 'time': datetime.utcnow()}) try: s...
Executes the measurement, recording the event status. :param duration: the time to run for. :return: nothing.
entailment
def calculateDelay(self, at, delay): """ Creates the delay from now til the specified start time, uses "at" if available. :param at: the start time in %a %b %d %H:%M:%S %Y format. :param delay: the delay from now til start. :return: the delay. """ if at is not Non...
Creates the delay from now til the specified start time, uses "at" if available. :param at: the start time in %a %b %d %H:%M:%S %Y format. :param delay: the delay from now til start. :return: the delay.
entailment
def launch_and_wait(mp_proc_list, pool_size): """ Given a list of multiprocessing.Process objects which have not yet been started, this function launches them and blocks until the last finishes. This makes sure that only <pool_size> processes are ever working at any one time (this number does not inclu...
Given a list of multiprocessing.Process objects which have not yet been started, this function launches them and blocks until the last finishes. This makes sure that only <pool_size> processes are ever working at any one time (this number does not include the main process which called this function, si...
entailment
def best_tile_layout(pool_size): """ Determine and return the best layout of "tiles" for fastest overall parallel processing of a rectangular image broken up into N smaller equally-sized rectangular tiles, given as input the number of processes/chunks which can be run/worked at the same time (pool_size)...
Determine and return the best layout of "tiles" for fastest overall parallel processing of a rectangular image broken up into N smaller equally-sized rectangular tiles, given as input the number of processes/chunks which can be run/worked at the same time (pool_size). This attempts to return a layout w...
entailment
def _accept(self): """ Work loop runs forever (or until running is False) :return: """ logger.warning("Reactor " + self._name + " is starting") while self.running: try: self._completeTask() except: logger.exception("...
Work loop runs forever (or until running is False) :return:
entailment
def offer(self, requestType, *args): """ public interface to the reactor. :param requestType: :param args: :return: """ if self._funcsByRequest.get(requestType) is not None: self._workQueue.put((requestType, list(*args))) else: logg...
public interface to the reactor. :param requestType: :param args: :return:
entailment
def clicked(self): """ Called when this button is clicked. Execute code from .cfgspc """ try: from . import teal except: teal = None try: # start drilling down into the tpo to get the code tealGui = self._mainGuiObj tealGui.show...
Called when this button is clicked. Execute code from .cfgspc
entailment
def ndarr2str(arr, encoding='ascii'): """ This is used to ensure that the return value of arr.tostring() is actually a string. This will prevent lots of if-checks in calling code. As of numpy v1.6.1 (in Python 3.2.3), the tostring() function still returns type 'bytes', not 'str' as it advertises. """ ...
This is used to ensure that the return value of arr.tostring() is actually a string. This will prevent lots of if-checks in calling code. As of numpy v1.6.1 (in Python 3.2.3), the tostring() function still returns type 'bytes', not 'str' as it advertises.
entailment
def ndarr2bytes(arr, encoding='ascii'): """ This is used to ensure that the return value of arr.tostring() is actually a *bytes* array in PY3K. See notes in ndarr2str above. Even though we consider it a bug that numpy's tostring() function returns a bytes array in PY3K, there are actually many instanc...
This is used to ensure that the return value of arr.tostring() is actually a *bytes* array in PY3K. See notes in ndarr2str above. Even though we consider it a bug that numpy's tostring() function returns a bytes array in PY3K, there are actually many instances where that is what we want - bytes, not u...
entailment
def tobytes(s, encoding='ascii'): """ Convert string s to the 'bytes' type, in all Pythons, even back before Python 2.6. What 'str' means varies by PY3K or not. In Pythons before 3.0, this is technically the same as the str type in terms of the character data in memory. """ # NOTE: after we abandon...
Convert string s to the 'bytes' type, in all Pythons, even back before Python 2.6. What 'str' means varies by PY3K or not. In Pythons before 3.0, this is technically the same as the str type in terms of the character data in memory.
entailment
def tostr(s, encoding='ascii'): """ Convert string-like-thing s to the 'str' type, in all Pythons, even back before Python 2.6. What 'str' means varies by PY3K or not. In Pythons before 3.0, str and bytes are the same type. In Python 3+, this may require a decoding step. """ if PY3K: if isi...
Convert string-like-thing s to the 'str' type, in all Pythons, even back before Python 2.6. What 'str' means varies by PY3K or not. In Pythons before 3.0, str and bytes are the same type. In Python 3+, this may require a decoding step.
entailment
def retry(func=None, retries=5, backoff=None, exceptions=(IOError, OSError, EOFError), cleanup=None, sleep=time.sleep): """ Decorator that retries the call ``retries`` times if ``func`` raises ``exceptions``. Can use a ``backoff`` function to sleep till next retry. Example:: >>> should_fail = ...
Decorator that retries the call ``retries`` times if ``func`` raises ``exceptions``. Can use a ``backoff`` function to sleep till next retry. Example:: >>> should_fail = lambda foo=[1,2,3]: foo and foo.pop() >>> @retry ... def flaky_func(): ... if should_fail(): ......
entailment
def loadSignal(self, name, start=None, end=None): """ Loads the named entry from the upload cache as a signal. :param name: the name. :param start: the time to start from in HH:mm:ss.SSS format :param end: the time to end at in HH:mm:ss.SSS format. :return: the signal if ...
Loads the named entry from the upload cache as a signal. :param name: the name. :param start: the time to start from in HH:mm:ss.SSS format :param end: the time to end at in HH:mm:ss.SSS format. :return: the signal if the named upload exists.
entailment
def _getCacheEntry(self, name): """ :param name: the name of the cache entry. :return: the entry or none. """ return next((x for x in self._uploadCache if x['name'] == name), None)
:param name: the name of the cache entry. :return: the entry or none.
entailment
def _convertTmp(self, tmpCacheEntry): """ Moves a tmp file to the upload dir, resampling it if necessary, and then deleting the tmp entries. :param tmpCacheEntry: the cache entry. :return: """ from analyser.common.signal import loadSignalFromWav tmpCacheEntry['sta...
Moves a tmp file to the upload dir, resampling it if necessary, and then deleting the tmp entries. :param tmpCacheEntry: the cache entry. :return:
entailment
def writeChunk(self, stream, filename, chunkIdx=None): """ Streams an uploaded chunk to a file. :param stream: the binary stream that contains the file. :param filename: the name of the file. :param chunkIdx: optional chunk index (for writing to a tmp dir) :return: no of...
Streams an uploaded chunk to a file. :param stream: the binary stream that contains the file. :param filename: the name of the file. :param chunkIdx: optional chunk index (for writing to a tmp dir) :return: no of bytes written or -1 if there was an error.
entailment
def finalise(self, filename, totalChunks, status): """ Completes the upload which means converting to a single 1kHz sample rate file output file. :param filename: :param totalChunks: :param status: :return: """ def getChunkIdx(x): try: ...
Completes the upload which means converting to a single 1kHz sample rate file output file. :param filename: :param totalChunks: :param status: :return:
entailment