idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
4,700
def month_days ( year , month ) : if month > 13 : raise ValueError ( "Incorrect month index" ) if month in ( IYYAR , TAMMUZ , ELUL , TEVETH , VEADAR ) : return 29 if month == ADAR and not leap ( year ) : return 29 if month == HESHVAN and ( year_days ( year ) % 10 ) != 5 : return 29 if month == KISLEV and ( year_days ( year ) % 10 ) == 3 : return 29 return 30
How many days are in a given month of a given year
4,701
def to_datetime ( jdc ) : year , month , day = gregorian . from_jd ( jdc ) frac = ( jdc + 0.5 ) % 1 hours = int ( 24 * frac ) mfrac = frac * 24 - hours mins = int ( 60 * round ( mfrac , 6 ) ) sfrac = mfrac * 60 - mins secs = int ( 60 * round ( sfrac , 6 ) ) msfrac = sfrac * 60 - secs ms = int ( 1000 * round ( msfrac , 6 ) ) return datetime ( year , month , day , int ( hours ) , int ( mins ) , int ( secs ) , int ( ms ) , tzinfo = utc )
Return a datetime for the input floating point Julian Day Count
4,702
def dbcon ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : self = args [ 0 ] if self . dbcon is None : self . dbcon = sqlite3 . connect ( self . db ) self . dbcur = self . dbcon . cursor ( ) self . dbcur . execute ( SQL_SENSOR_TABLE ) self . dbcur . execute ( SQL_TMPO_TABLE ) try : result = func ( * args , ** kwargs ) except Exception as e : self . dbcon . rollback ( ) self . dbcon . commit ( ) self . dbcon . close ( ) self . dbcon = None self . dbcur = None raise e else : self . dbcon . commit ( ) self . dbcon . close ( ) self . dbcon = None self . dbcur = None else : result = func ( * args , ** kwargs ) return result return wrapper
Set up connection before executing function commit and close connection afterwards . Unless a connection already has been created .
4,703
def add ( self , sid , token ) : try : self . dbcur . execute ( SQL_SENSOR_INS , ( sid , token ) ) except sqlite3 . IntegrityError : pass
Add new sensor to the database
4,704
def remove ( self , sid ) : self . dbcur . execute ( SQL_SENSOR_DEL , ( sid , ) ) self . dbcur . execute ( SQL_TMPO_DEL , ( sid , ) )
Remove sensor from the database
4,705
def list ( self , * sids ) : if sids == ( ) : sids = [ sid for ( sid , ) in self . dbcur . execute ( SQL_SENSOR_ALL ) ] slist = [ ] for sid in sids : tlist = [ ] for tmpo in self . dbcur . execute ( SQL_TMPO_ALL , ( sid , ) ) : tlist . append ( tmpo ) sid , rid , lvl , bid , ext , ctd , blk = tmpo self . _dprintf ( DBG_TMPO_WRITE , ctd , sid , rid , lvl , bid , len ( blk ) ) slist . append ( tlist ) return slist
List all tmpo - blocks in the database
4,706
def series ( self , sid , recycle_id = None , head = None , tail = None , datetime = True ) : if head is None : head = 0 else : head = self . _2epochs ( head ) if tail is None : tail = EPOCHS_MAX else : tail = self . _2epochs ( tail ) if recycle_id is None : self . dbcur . execute ( SQL_TMPO_RID_MAX , ( sid , ) ) recycle_id = self . dbcur . fetchone ( ) [ 0 ] tlist = self . list ( sid ) [ 0 ] srlist = [ ] for _sid , rid , lvl , bid , ext , ctd , blk in tlist : if ( recycle_id == rid and head < self . _blocktail ( lvl , bid ) and tail >= bid ) : srlist . append ( self . _blk2series ( ext , blk , head , tail ) ) if len ( srlist ) > 0 : ts = pd . concat ( srlist ) ts . name = sid if datetime is True : ts . index = pd . to_datetime ( ts . index , unit = "s" , utc = True ) return ts else : return pd . Series ( [ ] , name = sid )
Create data Series
4,707
def dataframe ( self , sids , head = 0 , tail = EPOCHS_MAX , datetime = True ) : if head is None : head = 0 else : head = self . _2epochs ( head ) if tail is None : tail = EPOCHS_MAX else : tail = self . _2epochs ( tail ) series = [ self . series ( sid , head = head , tail = tail , datetime = False ) for sid in sids ] df = pd . concat ( series , axis = 1 ) if datetime is True : df . index = pd . to_datetime ( df . index , unit = "s" , utc = True ) return df
Create data frame
4,708
def first_timestamp ( self , sid , epoch = False ) : first_block = self . dbcur . execute ( SQL_TMPO_FIRST , ( sid , ) ) . fetchone ( ) if first_block is None : return None timestamp = first_block [ 2 ] if not epoch : timestamp = pd . Timestamp . utcfromtimestamp ( timestamp ) timestamp = timestamp . tz_localize ( 'UTC' ) return timestamp
Get the first available timestamp for a sensor
4,709
def last_timestamp ( self , sid , epoch = False ) : timestamp , value = self . last_datapoint ( sid , epoch ) return timestamp
Get the theoretical last timestamp for a sensor
4,710
def addKwdArgsToSig ( sigStr , kwArgsDict ) : retval = sigStr if len ( kwArgsDict ) > 0 : retval = retval . strip ( ' ,)' ) for k in kwArgsDict : if retval [ - 1 ] != '(' : retval += ", " retval += str ( k ) + "=" + str ( kwArgsDict [ k ] ) retval += ')' retval = retval return retval
Alter the passed function signature string to add the given kewords
4,711
def _gauss_funct ( p , fjac = None , x = None , y = None , err = None , weights = None ) : 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 ) ) status = 0 if weights is not None : if err is not None : print ( "Warning: Ignoring errors and using weights.\n" ) return [ status , ( y - model ) * weights ] elif err is not None : return [ status , ( y - model ) / err ] else : return [ status , y - model ]
Defines the gaussian function to be used as the model .
4,712
def gfit1d ( y , x = None , err = None , weights = None , par = None , parinfo = None , maxiter = 200 , quiet = 0 ) : y = y . astype ( np . float ) if weights is not None : weights = weights . astype ( np . float ) if err is not None : err = err . astype ( np . float ) if x is None and len ( y . shape ) == 1 : x = np . arange ( len ( y ) ) . astype ( np . float ) if x . shape != y . shape : print ( "input arrays X and Y must be of equal shape.\n" ) return fa = { 'x' : x , 'y' : y , 'err' : err , 'weights' : weights } if par is not None : p = par else : ysigma = y . std ( ) ind = np . nonzero ( y > ysigma ) [ 0 ] if len ( ind ) != 0 : xind = int ( ind . mean ( ) ) p2 = x [ xind ] p1 = y [ xind ] p3 = 1.0 else : ymax = y . max ( ) ymin = y . min ( ) ymean = y . mean ( ) if ( ymax - ymean ) > ( abs ( ymin - ymean ) ) : p1 = ymax else : p1 = ymin ind = ( np . nonzero ( y == p1 ) ) [ 0 ] p2 = x . mean ( ) p3 = 1. p = [ p1 , p2 , p3 ] m = nmpfit . mpfit ( _gauss_funct , p , parinfo = parinfo , functkw = fa , maxiter = maxiter , quiet = quiet ) if ( m . status <= 0 ) : print ( 'error message = ' , m . errmsg ) return m
Return the gaussian fit as an object .
4,713
def filter ( self , * args , ** kwargs ) : 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 .
4,714
def _extract_model_params ( self , defaults , ** kwargs ) : obj = kwargs . pop ( self . object_property_name , None ) if obj is not None : kwargs [ 'object_hash' ] = self . model . _compute_hash ( obj ) lookup , params = super ( ) . _extract_model_params ( defaults , ** kwargs ) if obj is not None : params [ self . object_property_name ] = obj del params [ 'object_hash' ] return lookup , params
this method allows django managers use objects . get_or_create and objects . update_or_create on a hashable object .
4,715
def persist ( self ) : 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 ( ) self . _persisted = True return self . _persisted
a private method that persists an estimator object to the filesystem
4,716
def load ( self ) : 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
4,717
def create_from_file ( cls , filename ) : 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
4,718
def getAppDir ( ) : theDir = os . path . expanduser ( '~/.' ) + APP_NAME . lower ( ) if not os . path . exists ( theDir ) : try : os . mkdir ( theDir ) except OSError : print ( 'Could not create "' + theDir + '" to save GUI settings.' ) theDir = "./" + APP_NAME . lower ( ) return theDir
Return our application dir . Create it if it doesn t exist .
4,719
def getEmbeddedKeyVal ( cfgFileName , kwdName , dflt = None ) : try : junkObj = configobj . ConfigObj ( cfgFileName , list_values = False ) except : if kwdName == TASK_NAME_KEY : raise KeyError ( 'Can not parse as a parameter config file: ' + '\n\t' + os . path . realpath ( cfgFileName ) ) else : raise KeyError ( 'Unfound key "' + kwdName + '" while parsing: ' + '\n\t' + os . path . realpath ( cfgFileName ) ) if kwdName in junkObj : retval = junkObj [ kwdName ] del junkObj return retval if dflt is not None : del junkObj return dflt else : if kwdName == TASK_NAME_KEY : raise KeyError ( 'Can not parse as a parameter config file: ' + '\n\t' + os . path . realpath ( cfgFileName ) ) else : raise KeyError ( 'Unfound key "' + kwdName + '" while parsing: ' + '\n\t' + os . path . realpath ( cfgFileName ) )
Read a config file and pull out the value of a given keyword .
4,720
def getCfgFilesInDirForTask ( aDir , aTask , recurse = False ) : if recurse : flist = irafutils . rglob ( aDir , '*.cfg' ) else : flist = glob . glob ( aDir + os . sep + '*.cfg' ) if aTask : retval = [ ] for f in flist : try : if aTask == getEmbeddedKeyVal ( f , TASK_NAME_KEY , '' ) : retval . append ( f ) except Exception as e : print ( 'Warning: ' + str ( e ) ) return retval else : return flist
This is a specialized function which is meant only to keep the same code from needlessly being much repeated throughout this application . This must be kept as fast and as light as possible . This checks a given directory for . cfg files matching a given task . If recurse is True it will check subdirectories . If aTask is None it returns all files and ignores aTask .
4,721
def getUsrCfgFilesForPyPkg ( pkgName ) : thePkg , theFile = findCfgFileForPkg ( pkgName , '.cfg' ) tname = getEmbeddedKeyVal ( theFile , TASK_NAME_KEY ) flist = getCfgFilesInDirForTask ( getAppDir ( ) , tname ) return flist
See if the user has one of their own local . cfg files for this task such as might be created automatically during the save of a read - only package and return their names .
4,722
def checkSetReadOnly ( fname , raiseOnErr = False ) : if os . access ( fname , os . W_OK ) : irafutils . setWritePrivs ( fname , False , ignoreErrors = not raiseOnErr )
See if we have write - privileges to this file . If we do and we are not supposed to then fix that case .
4,723
def isHiddenName ( astr ) : if astr is not None and len ( astr ) > 2 and astr . startswith ( '_' ) and astr . endswith ( '_' ) : return True else : return False
Return True if this string name denotes a hidden par or section
4,724
def syncParamList ( self , firstTime , preserve_order = True ) : new_list = self . _getParamsFromConfigDict ( self , initialPass = firstTime ) if self . _forUseWithEpar : new_list . append ( basicpar . IrafParS ( [ '$nargs' , 's' , 'h' , 'N' ] ) ) if len ( self . __paramList ) > 0 and preserve_order : namesInOrder = [ p . fullName ( ) for p in self . __paramList ] assert len ( namesInOrder ) == len ( new_list ) , 'Mismatch in num pars, had: ' + str ( len ( namesInOrder ) ) + ', now we have: ' + str ( len ( new_list ) ) + ', ' + str ( [ p . fullName ( ) for p in new_list ] ) self . __paramList [ : ] = [ ] new_list_dict = { } for par in new_list : new_list_dict [ par . fullName ( ) ] = par for fn in namesInOrder : self . __paramList . append ( new_list_dict [ fn ] ) else : self . __paramList [ : ] = new_list
Set or reset the internal param list from the dict s contents .
4,725
def getDefaultParList ( self ) : if self . filename is None : self . filename = self . getDefaultSaveFilename ( stub = True ) return copy . deepcopy ( self . __paramList ) tmpObj = ConfigObjPars ( self . filename , associatedPkg = self . __assocPkg , setAllToDefaults = True , strict = False ) return tmpObj . getParList ( )
Return a par list just like ours but with all default values .
4,726
def run ( self , * args , ** kw ) : if self . _runFunc is not None : if 'mode' in kw : kw . pop ( 'mode' ) if '_save' in kw : kw . pop ( '_save' ) return self . _runFunc ( self , * args , ** kw ) else : raise taskpars . NoExecError ( 'No way to run task "' + self . __taskName + '". You must either override the "run" method in your ' + 'ConfigObjPars subclass, or you must supply a "run" ' + 'function in your package.' )
This may be overridden by a subclass .
4,727
def triggerLogicToStr ( self ) : try : import json except ImportError : return "Cannot dump triggers/dependencies/executes (need json)" retval = "TRIGGERS:\n" + json . dumps ( self . _allTriggers , indent = 3 ) retval += "\nDEPENDENCIES:\n" + json . dumps ( self . _allDepdcs , indent = 3 ) retval += "\nTO EXECUTE:\n" + json . dumps ( self . _allExecutes , indent = 3 ) retval += "\n" return retval
Print all the trigger logic to a string and return it .
4,728
def _findAssociatedConfigSpecFile ( self , cfgFileName ) : retval = "." + os . sep + self . __taskName + ".cfgspc" if os . path . isfile ( retval ) : return retval retval = os . path . dirname ( cfgFileName ) + os . sep + self . __taskName + ".cfgspc" if os . path . isfile ( retval ) : return retval retval = self . getDefaultSaveFilename ( ) + 'spc' if os . path . isfile ( retval ) : return retval if self . __assocPkg is not None : x , theFile = findCfgFileForPkg ( None , '.cfgspc' , pkgObj = self . __assocPkg , taskName = self . __taskName ) return theFile x , theFile = findCfgFileForPkg ( self . __taskName , '.cfgspc' , taskName = self . __taskName ) if os . path . exists ( theFile ) : return theFile raise NoCfgFileError ( 'Unfound config-spec file for task: "' + self . __taskName + '"' )
Given a config file find its associated config - spec file and return the full pathname of the file .
4,729
def getPosArgs ( self ) : if len ( self . _posArgs ) < 1 : return [ ] self . _posArgs . sort ( ) retval = [ ] for idx , scope , name in self . _posArgs : theDict , val = findScopedPar ( self , scope , name ) retval . append ( val ) return retval
Return a list in order of any parameters marked with pos = N in the . cfgspc file .
4,730
def dottedQuadToNum ( ip ) : import socket , struct try : return struct . unpack ( '!L' , socket . inet_aton ( ip . strip ( ) ) ) [ 0 ] except socket . error : raise ValueError ( 'Not a good dotted-quad IP: %s' % ip ) return
Convert decimal dotted quad string to long integer
4,731
def numToDottedQuad ( num ) : import socket , struct if num > 4294967295 or num < 0 : raise ValueError ( 'Not a good numeric IP: %s' % num ) try : return socket . inet_ntoa ( struct . pack ( '!L' , long ( num ) ) ) except ( socket . error , struct . error , OverflowError ) : raise ValueError ( 'Not a good numeric IP: %s' % num )
Convert long int to dotted quad string
4,732
def _is_num_param ( names , values , to_float = False ) : fun = to_float and float or int out_params = [ ] for ( name , val ) in zip ( names , values ) : if val is None : out_params . append ( val ) elif isinstance ( val , number_or_string_types ) : try : out_params . append ( fun ( val ) ) except ValueError : raise VdtParamError ( name , val ) else : raise VdtParamError ( name , val ) return out_params
Return numbers from inputs or raise VdtParamError .
4,733
def is_boolean ( value ) : if isinstance ( value , string_types ) : try : return bool_dict [ value . lower ( ) ] except KeyError : raise VdtTypeError ( value ) if value == False : return False elif value == True : return True else : raise VdtTypeError ( value )
Check if the value represents a boolean .
4,734
def is_ip_addr ( value ) : if not isinstance ( value , string_types ) : raise VdtTypeError ( value ) value = value . strip ( ) try : dottedQuadToNum ( value ) except ValueError : raise VdtValueError ( value ) return value
Check that the supplied value is an Internet Protocol address v . 4 represented by a dotted - quad string i . e . 1 . 2 . 3 . 4 .
4,735
def is_list ( value , min = None , max = None ) : ( min_len , max_len ) = _is_num_param ( ( 'min' , 'max' ) , ( min , max ) ) if isinstance ( value , string_types ) : raise VdtTypeError ( value ) try : num_members = len ( value ) except TypeError : raise VdtTypeError ( value ) if min_len is not None and num_members < min_len : raise VdtValueTooShortError ( value ) if max_len is not None and num_members > max_len : raise VdtValueTooLongError ( value ) return list ( value )
Check that the value is a list of values .
4,736
def is_int_list ( value , min = None , max = None ) : return [ is_integer ( mem ) for mem in is_list ( value , min , max ) ]
Check that the value is a list of integers .
4,737
def is_bool_list ( value , min = None , max = None ) : return [ is_boolean ( mem ) for mem in is_list ( value , min , max ) ]
Check that the value is a list of booleans .
4,738
def is_float_list ( value , min = None , max = None ) : return [ is_float ( mem ) for mem in is_list ( value , min , max ) ]
Check that the value is a list of floats .
4,739
def is_string_list ( value , min = None , max = None ) : if isinstance ( value , string_types ) : raise VdtTypeError ( value ) return [ is_string ( mem ) for mem in is_list ( value , min , max ) ]
Check that the value is a list of strings .
4,740
def is_ip_addr_list ( value , min = None , max = None ) : return [ is_ip_addr ( mem ) for mem in is_list ( value , min , max ) ]
Check that the value is a list of IP addresses .
4,741
def force_list ( value , min = None , max = None ) : if not isinstance ( value , ( list , tuple ) ) : value = [ value ] return is_list ( value , min , max )
Check that a value is a list coercing strings into a list with one member . Useful where users forget the trailing comma that turns a single value into a list .
4,742
def is_mixed_list ( value , * args ) : try : length = len ( value ) except TypeError : raise VdtTypeError ( value ) if length < len ( args ) : raise VdtValueTooShortError ( value ) elif length > len ( args ) : raise VdtValueTooLongError ( value ) try : return [ fun_dict [ arg ] ( val ) for arg , val in zip ( args , value ) ] except KeyError as e : raise ( VdtParamError ( 'mixed_list' , e ) )
Check that the value is a list . Allow specifying the type of each member . Work on lists of specific lengths .
4,743
def is_option ( value , * options ) : if not isinstance ( value , string_types ) : raise VdtTypeError ( value ) if not value in options : raise VdtValueError ( value ) return value
This check matches the value to any of a set of options .
4,744
def _unquote ( self , val ) : if ( len ( val ) >= 2 ) and ( val [ 0 ] in ( "'" , '"' ) ) and ( val [ 0 ] == val [ - 1 ] ) : val = val [ 1 : - 1 ] return val
Unquote a value if necessary .
4,745
def match_header ( cls , header ) : pixvalue = header . get ( 'PIXVALUE' ) naxis = header . get ( 'NAXIS' , 0 ) return ( super ( _ConstantValueImageBaseHDU , cls ) . match_header ( header ) and ( isinstance ( pixvalue , float ) or _is_int ( pixvalue ) ) and naxis == 0 )
A constant value HDU will only be recognized as such if the header contains a valid PIXVALUE and NAXIS == 0 .
4,746
def _check_constant_value_data ( self , data ) : arrayval = data . flat [ 0 ] if np . all ( data == arrayval ) : return arrayval return None
Verify that the HDU s data is a constant value array .
4,747
def dumps ( columns ) : fp = BytesIO ( ) dump ( columns , fp ) fp . seek ( 0 ) return fp . read ( )
Serialize columns to a JSON formatted bytes object .
4,748
def readall ( cls , member , size ) : fp = member . library . fp LINE = member . library . LINE n = cls . header_match ( fp . read ( LINE ) ) namestrs = [ fp . read ( size ) for i in range ( n ) ] remainder = n * size % LINE if remainder : padding = 80 - remainder fp . read ( padding ) info = [ cls . unpack ( s ) for s in namestrs ] for d in info : d [ 'format' ] = Format ( ** d [ 'format' ] ) d [ 'iformat' ] = InputFormat ( ** d [ 'iformat' ] ) return [ Variable ( ** d ) for d in info ]
Parse variable metadata for a XPORT file member .
4,749
def to_jd ( year , month , day ) : return ( day + ceil ( 29.5 * ( month - 1 ) ) + ( year - 1 ) * 354 + trunc ( ( 3 + ( 11 * year ) ) / 30 ) + EPOCH ) - 1
Determine Julian day count from Islamic date
4,750
def from_jd ( jd ) : jd = trunc ( jd ) + 0.5 year = trunc ( ( ( 30 * ( jd - EPOCH ) ) + 10646 ) / 10631 ) month = min ( 12 , ceil ( ( jd - ( 29 + to_jd ( year , 1 , 1 ) ) ) / 29.5 ) + 1 ) day = int ( jd - to_jd ( year , month , 1 ) ) + 1 return ( year , month , day )
Calculate Islamic date from Julian day
4,751
def freshenFocus ( self ) : self . top . update_idletasks ( ) self . top . after ( 10 , self . setViewAtTop )
Did something which requires a new look . Move scrollbar up . This often needs to be delayed a bit however to let other events in the queue through first .
4,752
def mwl ( self , event ) : if event . num == 4 : self . top . f . canvas . yview_scroll ( - 1 * self . _tmwm , 'units' ) elif event . num == 5 : self . top . f . canvas . yview_scroll ( 1 * self . _tmwm , 'units' ) else : self . top . f . canvas . yview_scroll ( - ( event . delta ) * self . _tmwm , 'units' )
Mouse Wheel - under tkinter we seem to need Tk v8 . 5 + for this
4,753
def focusNext ( self , event ) : try : event . widget . tk_focusNext ( ) . focus_set ( ) except TypeError : name = event . widget . tk . call ( 'tk_focusNext' , event . widget . _w ) event . widget . _nametowidget ( str ( name ) ) . focus_set ( )
Set focus to next item in sequence
4,754
def focusPrev ( self , event ) : try : event . widget . tk_focusPrev ( ) . focus_set ( ) except TypeError : name = event . widget . tk . call ( 'tk_focusPrev' , event . widget . _w ) event . widget . _nametowidget ( str ( name ) ) . focus_set ( )
Set focus to previous item in sequence
4,755
def doScroll ( self , event ) : canvas = self . top . f . canvas widgetWithFocus = event . widget if widgetWithFocus is self . lastFocusWidget : return FALSE self . lastFocusWidget = widgetWithFocus if widgetWithFocus is None : return TRUE y1 = widgetWithFocus . winfo_rooty ( ) y2 = y1 + widgetWithFocus . winfo_height ( ) cy1 = canvas . winfo_rooty ( ) cy2 = cy1 + canvas . winfo_height ( ) yinc = self . yscrollincrement if y1 < cy1 : sdist = int ( ( y1 - cy1 - yinc + 1. ) / yinc ) canvas . yview_scroll ( sdist , "units" ) elif cy2 < y2 : sdist = int ( ( y2 - cy2 + yinc - 1. ) / yinc ) canvas . yview_scroll ( sdist , "units" ) return TRUE
Scroll the panel down to ensure widget with focus to be visible
4,756
def _handleParListMismatch ( self , probStr , extra = False ) : errmsg = 'ERROR: mismatch between default and current par lists ' + 'for task "' + self . taskName + '"' if probStr : errmsg += '\n\t' + probStr errmsg += '\n(try: "unlearn ' + self . taskName + '")' print ( errmsg ) return False
Handle the situation where two par lists do not match . This is meant to allow subclasses to override . Note that this only handles missing pars and extra pars not wrong - type pars .
4,757
def _setupDefaultParamList ( self ) : self . defaultParamList = self . _taskParsObj . getDefaultParList ( ) theParamList = self . _taskParsObj . getParList ( ) if len ( self . defaultParamList ) != len ( theParamList ) : pmsg = 'Current list not same length as default list' if not self . _handleParListMismatch ( pmsg ) : return False ourpardict = { } for par in theParamList : ourpardict [ par . fullName ( ) ] = par sortednames = [ p . fullName ( ) for p in self . defaultParamList ] migrated = [ ] newList = [ ] for fullName in sortednames : if fullName in ourpardict : newList . append ( ourpardict [ fullName ] ) migrated . append ( fullName ) else : theDfltVer = [ p for p in self . defaultParamList if p . fullName ( ) == fullName ] newList . append ( copy . deepcopy ( theDfltVer [ 0 ] ) ) theParamList [ : ] = newList extras = [ fn for fn in ourpardict if not fn in migrated ] for fullName in extras : if not self . _handleParListMismatch ( 'Unexpected par: "' + fullName + '"' , extra = True ) : return False print ( 'Ignoring unexpected par: "' + p + '"' ) return True
This creates self . defaultParamList . It also does some checks on the paramList sets its order if needed and deletes any extra or unknown pars if found . We assume the order of self . defaultParamList is the correct order .
4,758
def saveAs ( self , event = None ) : self . debug ( 'Clicked Save as...' ) curdir = os . getcwd ( ) writeProtChoice = self . _writeProtectOnSaveAs if capable . OF_TKFD_IN_EPAR : fname = asksaveasfilename ( parent = self . top , title = 'Save Parameter File As' , defaultextension = self . _defSaveAsExt , initialdir = os . path . dirname ( self . _getSaveAsFilter ( ) ) ) else : from . import filedlg fd = filedlg . PersistSaveFileDialog ( self . top , "Save Parameter File As" , self . _getSaveAsFilter ( ) , initWProtState = writeProtChoice ) if fd . Show ( ) != 1 : fd . DialogCleanup ( ) os . chdir ( curdir ) return fname = fd . GetFileName ( ) writeProtChoice = fd . GetWriteProtectChoice ( ) fd . DialogCleanup ( ) if not fname : return if self . checkSetSaveChildren ( ) : os . chdir ( curdir ) return self . _saveAsPreSave_Hook ( fname ) self . badEntriesList = self . checkSetSaveEntries ( doSave = False ) if self . badEntriesList : ansOKCANCEL = self . processBadEntries ( self . badEntriesList , self . taskName ) if not ansOKCANCEL : os . chdir ( curdir ) return mstr = "TASKMETA: task=" + self . taskName + " package=" + self . pkgName if self . checkSetSaveEntries ( doSave = True , filename = fname , comment = mstr , set_ro = writeProtChoice , overwriteRO = True ) : os . chdir ( curdir ) raise Exception ( "Unexpected bad entries for: " + self . taskName ) self . _saveAsPostSave_Hook ( fname ) os . chdir ( curdir )
Save the parameter settings to a user - specified file . Any changes here must be coordinated with the corresponding tpar save_as function .
4,759
def htmlHelp ( self , helpString = None , title = None , istask = False , tag = None ) : if not helpString : helpString = self . getHelpString ( self . pkgName + '.' + self . taskName ) if not title : title = self . taskName lwr = helpString . lower ( ) if lwr . startswith ( "http:" ) or lwr . startswith ( "https:" ) or lwr . startswith ( "file:" ) : url = helpString if tag and url . find ( '#' ) < 0 : url += '#' + tag irafutils . launchBrowser ( url , subj = title ) else : ( fd , fname ) = tempfile . mkstemp ( suffix = '.html' , prefix = 'editpar_' ) os . close ( fd ) f = open ( fname , 'w' ) if istask and self . _knowTaskHelpIsHtml : f . write ( helpString ) else : f . write ( '<html><head><title>' + title + '</title></head>\n' ) f . write ( '<body><h3>' + title + '</h3>\n' ) f . write ( '<pre>\n' + helpString + '\n</pre></body></html>' ) f . close ( ) irafutils . launchBrowser ( "file://" + fname , subj = title )
Pop up the help in a browser window . By default this tries to show the help for the current task . With the option arguments it can be used to show any help string .
4,760
def getValue ( self , name , scope = None , native = False ) : theParamList = self . _taskParsObj . getParList ( ) fullName = basicpar . makeFullName ( scope , name ) for i in range ( self . numParams ) : par = theParamList [ i ] entry = self . entryNo [ i ] if par . fullName ( ) == fullName or ( scope is None and par . name == name ) : if native : return entry . convertToNative ( entry . choice . get ( ) ) else : return entry . choice . get ( ) raise RuntimeError ( 'Could not find par: "' + fullName + '"' )
Return current par value from the GUI . This does not do any validation and it it not necessarily the same value saved in the model which is always behind the GUI setting in time . This is NOT to be used to get all the values - it would not be efficient .
4,761
def _pushMessages ( self ) : self . showStatus ( '' ) if len ( self . _statusMsgsToShow ) > 0 : self . top . after ( 200 , self . _pushMessages )
Internal callback used to make sure the msg list keeps moving .
4,762
def teal ( theTask , parent = None , loadOnly = False , returnAs = "dict" , canExecute = True , strict = False , errorsToTerm = False , autoClose = True , defaults = False ) : if loadOnly : obj = None try : obj = cfgpars . getObjectFromTaskArg ( theTask , strict , defaults ) except Exception as re : if strict : raise else : print ( re . message . replace ( '\n\n' , '\n' ) ) return obj else : assert returnAs in ( "dict" , "status" , None ) , "Invalid value for returnAs arg: " + str ( returnAs ) dlg = None try : if defaults : theTask = cfgpars . getObjectFromTaskArg ( theTask , strict , True ) dlg = ConfigObjEparDialog ( theTask , parent = parent , autoClose = autoClose , strict = strict , canExecute = canExecute ) except cfgpars . NoCfgFileError as ncf : log_last_error ( ) if errorsToTerm : print ( str ( ncf ) . replace ( '\n\n' , '\n' ) ) else : popUpErr ( parent = parent , message = str ( ncf ) , title = "Unfound Task" ) except Exception as re : log_last_error ( ) if errorsToTerm : print ( re . message . replace ( '\n\n' , '\n' ) ) else : popUpErr ( parent = parent , message = re . message , title = "Bad Parameters" ) if returnAs is None : return if returnAs == "dict" : if dlg is None or dlg . canceled ( ) : return None else : return dlg . getTaskParsObj ( ) if dlg is None or dlg . canceled ( ) : return - 1 if dlg . executed ( ) : return 1 return 0
Start the GUI session or simply load a task s ConfigObj .
4,763
def load ( theTask , canExecute = True , strict = True , defaults = False ) : return teal ( theTask , parent = None , loadOnly = True , returnAs = "dict" , canExecute = canExecute , strict = strict , errorsToTerm = True , defaults = defaults )
Shortcut to load TEAL . cfg files for non - GUI access where loadOnly = True .
4,764
def cfgGetBool ( theObj , name , dflt ) : strval = theObj . get ( name , None ) if strval is None : return dflt return strval . lower ( ) . strip ( ) == 'true'
Get a stringified val from a ConfigObj obj and return it as bool
4,765
def _overrideMasterSettings ( self ) : cod = self . _getGuiSettings ( ) self . _appName = APP_NAME self . _appHelpString = tealHelpString self . _useSimpleAutoClose = self . _do_usac self . _showExtraHelpButton = False self . _saveAndCloseOnExec = cfgGetBool ( cod , 'saveAndCloseOnExec' , True ) self . _showHelpInBrowser = cfgGetBool ( cod , 'showHelpInBrowser' , False ) self . _writeProtectOnSaveAs = cfgGetBool ( cod , 'writeProtectOnSaveAsOpt' , True ) self . _flagNonDefaultVals = cfgGetBool ( cod , 'flagNonDefaultVals' , None ) self . _optFile = APP_NAME . lower ( ) + ".optionDB" ltblu = "#ccccff" drktl = "#008888" self . _frmeColor = cod . get ( 'frameColor' , drktl ) self . _taskColor = cod . get ( 'taskBoxColor' , ltblu ) self . _bboxColor = cod . get ( 'buttonBoxColor' , ltblu ) self . _entsColor = cod . get ( 'entriesColor' , ltblu ) self . _flagColor = cod . get ( 'flaggedColor' , 'brown' ) if self . _canExecute and self . _taskParsObj : self . _canExecute = self . _taskParsObj . canExecute ( ) self . _showExecuteButton = self . _canExecute hhh = self . getHelpString ( self . pkgName + '.' + self . taskName ) if hhh : hhh = hhh . lower ( ) if hhh . find ( '<html' ) >= 0 or hhh . find ( '</html>' ) > 0 : self . _knowTaskHelpIsHtml = True elif hhh . startswith ( 'http:' ) or hhh . startswith ( 'https:' ) : self . _knowTaskHelpIsHtml = True elif hhh . startswith ( 'file:' ) and ( hhh . endswith ( '.htm' ) or hhh . endswith ( '.html' ) ) : self . _knowTaskHelpIsHtml = True
Override so that we can run in a different mode .
4,766
def _doActualSave ( self , fname , comment , set_ro = False , overwriteRO = False ) : self . debug ( 'Saving, file name given: ' + str ( fname ) + ', set_ro: ' + str ( set_ro ) + ', overwriteRO: ' + str ( overwriteRO ) ) cantWrite = False inInstArea = False if fname in ( None , '' ) : fname = self . _taskParsObj . getFilename ( ) try : if _isInstalled ( fname ) : inInstArea = cantWrite = True else : if overwriteRO and os . path . exists ( fname ) : setWritePrivs ( fname , True , True ) rv = self . _taskParsObj . saveParList ( filename = fname , comment = comment ) except IOError : cantWrite = True if cantWrite : fname = self . _taskParsObj . getDefaultSaveFilename ( ) msg = 'Read-only config file for task "' if inInstArea : msg = 'Installed config file for task "' msg += self . _taskParsObj . getName ( ) + '" is not to be overwritten.' + ' Values will be saved to: \n\n\t"' + fname + '".' showwarning ( message = msg , title = "Will not overwrite!" ) rv = self . _taskParsObj . saveParList ( filename = fname , comment = comment ) self . _saveAsPostSave_Hook ( fname ) if set_ro and os . path . dirname ( os . path . abspath ( fname ) ) != os . path . abspath ( self . _rcDir ) : cfgpars . checkSetReadOnly ( fname ) self . _lastSavedState = self . _taskParsObj . dict ( ) return rv
Override this so we can handle case of file not writable as well as to make our _lastSavedState copy .
4,767
def _defineEditedCallbackObjectFor ( self , parScope , parName ) : triggerStrs = self . _taskParsObj . getTriggerStrings ( parScope , parName ) if triggerStrs and len ( triggerStrs ) > 0 : return self else : return None
Override to allow us to use an edited callback .
4,768
def updateTitle ( self , atitle ) : if atitle and os . path . exists ( atitle ) : if _isInstalled ( atitle ) : atitle += ' [installed]' elif not os . access ( atitle , os . W_OK ) : atitle += ' [read only]' super ( ConfigObjEparDialog , self ) . updateTitle ( atitle )
Override so we can append read - only status .
4,769
def edited ( self , scope , name , lastSavedVal , newVal , action ) : triggerNamesTup = self . _taskParsObj . getTriggerStrings ( scope , name ) assert triggerNamesTup is not None and len ( triggerNamesTup ) > 0 , 'Empty trigger name for: "' + name + '", consult the .cfgspc file.' for triggerName in triggerNamesTup : if triggerName == '_section_switch_' : state = newVal not in self . FALSEVALS self . _toggleSectionActiveState ( scope , state , ( name , ) ) continue if triggerName == '_2_section_switch_' : state = newVal not in self . FALSEVALS self . _toggleSectionActiveState ( scope , state , ( name , ) ) fpons = self . findNextSection ( scope , name ) nextSectScope = fpons [ 0 ] if nextSectScope : self . _toggleSectionActiveState ( nextSectScope , state , None ) continue if '_RULES_' in self . _taskParsObj and triggerName in self . _taskParsObj [ '_RULES_' ] . configspec : ruleSig = self . _taskParsObj [ '_RULES_' ] . configspec [ triggerName ] chkArgsDict = vtor_checks . sigStrToKwArgsDict ( ruleSig ) codeStr = chkArgsDict . get ( 'code' ) when2run = chkArgsDict . get ( 'when' ) greenlight = False if when2run is None : greenlight = True else : assert action in editpar . GROUP_ACTIONS , "Unknown action: " + str ( action ) + ', expected one of: ' + str ( editpar . GROUP_ACTIONS ) whenlist = when2run . split ( ',' ) for w in whenlist : if not w in editpar . GROUP_ACTIONS and w != 'always' : print ( 'WARNING: skipping bad value for when kwd: "' + w + '" in trigger/rule: ' + triggerName ) greenlight = 'always' in whenlist or action in whenlist if codeStr : if not greenlight : continue self . showStatus ( "Evaluating " + triggerName + ' ...' ) self . top . update_idletasks ( ) try : outval = execEmbCode ( scope , name , newVal , self , codeStr ) except Exception as ex : outval = 'ERROR in ' + triggerName + ': ' + str ( ex ) print ( outval ) msg = outval + ':\n' + ( '-' * 99 ) + '\n' + traceback . format_exc ( ) msg += 'CODE: ' + codeStr + '\n' + '-' * 99 + '\n' self . debug ( msg ) self . showStatus ( outval , keep = 1 ) msg = 'Value of "' + name + '" triggered "' + triggerName + '"' stroutval = str ( outval ) if len ( stroutval ) < 30 : msg += ' + stroutval + '"' self . showStatus ( msg , keep = 0 ) self . _applyTriggerValue ( triggerName , outval ) continue raise RuntimeError ( 'Unknown trigger for: "' + name + '", named: "' + str ( triggerName ) + '". Please consult the .cfgspc file.' )
This is the callback function invoked when an item is edited . This is only called for those items which were previously specified to use this mechanism . We do not turn this on for all items because the performance might be prohibitive . This kicks off any previously registered triggers .
4,770
def _setTaskParsObj ( self , theTask ) : self . _taskParsObj = cfgpars . getObjectFromTaskArg ( theTask , self . _strict , False ) self . _taskParsObj . setDebugLogger ( self ) self . _lastSavedState = self . _taskParsObj . dict ( )
Overridden version for ConfigObj . theTask can be either a . cfg file name or a ConfigObjPars object .
4,771
def _getSaveAsFilter ( self ) : absRcDir = os . path . abspath ( self . _rcDir ) thedir = os . path . abspath ( os . path . dirname ( self . _taskParsObj . filename ) ) if thedir == absRcDir or not os . access ( thedir , os . W_OK ) : thedir = os . path . abspath ( os . path . curdir ) filt = thedir + '/*.cfg' envVarName = APP_NAME . upper ( ) + '_CFG' if envVarName in os . environ : upx = os . environ [ envVarName ] if len ( upx ) > 0 : filt = upx + "/*.cfg" return filt
Return a string to be used as the filter arg to the save file dialog during Save - As .
4,772
def _getOpenChoices ( self ) : tsk = self . _taskParsObj . getName ( ) taskFiles = set ( ) dirsSoFar = [ ] aDir = os . path . dirname ( self . _taskParsObj . filename ) if len ( aDir ) < 1 : aDir = os . curdir dirsSoFar . append ( aDir ) taskFiles . update ( cfgpars . getCfgFilesInDirForTask ( aDir , tsk ) ) aDir = os . getcwd ( ) if aDir not in dirsSoFar : dirsSoFar . append ( aDir ) taskFiles . update ( cfgpars . getCfgFilesInDirForTask ( aDir , tsk ) ) try : x , pkgf = cfgpars . findCfgFileForPkg ( tsk , '.cfg' , taskName = tsk , pkgObj = self . _taskParsObj . getAssocPkg ( ) ) taskFiles . update ( ( pkgf , ) ) except cfgpars . NoCfgFileError : pass aDir = self . _rcDir if aDir not in dirsSoFar : dirsSoFar . append ( aDir ) taskFiles . update ( cfgpars . getCfgFilesInDirForTask ( aDir , tsk ) ) aDir = dirsSoFar [ 0 ] envVarName = APP_NAME . upper ( ) + '_CFG' if envVarName in os . environ : aDir = os . environ [ envVarName ] if aDir not in dirsSoFar : dirsSoFar . append ( aDir ) taskFiles . update ( cfgpars . getCfgFilesInDirForTask ( aDir , tsk ) ) taskFiles = list ( taskFiles ) taskFiles . sort ( ) taskFiles . append ( "Other ..." ) return taskFiles
Go through all possible sites to find applicable . cfg files . Return as an iterable .
4,773
def pfopen ( self , event = None ) : fname = self . _openMenuChoice . get ( ) if fname [ - 3 : ] == '...' : if capable . OF_TKFD_IN_EPAR : fname = askopenfilename ( title = "Load Config File" , parent = self . top ) else : from . import filedlg fd = filedlg . PersistLoadFileDialog ( self . top , "Load Config File" , self . _getSaveAsFilter ( ) ) if fd . Show ( ) != 1 : fd . DialogCleanup ( ) return fname = fd . GetFileName ( ) fd . DialogCleanup ( ) if not fname : return self . debug ( 'Loading from: ' + fname ) try : tmpObj = cfgpars . ConfigObjPars ( fname , associatedPkg = self . _taskParsObj . getAssocPkg ( ) , strict = self . _strict ) except Exception as ex : showerror ( message = ex . message , title = 'Error in ' + os . path . basename ( fname ) ) self . debug ( 'Error in ' + os . path . basename ( fname ) ) self . debug ( traceback . format_exc ( ) ) return if not self . _taskParsObj . isSameTaskAs ( tmpObj ) : msg = 'The current task is "' + self . _taskParsObj . getName ( ) + '", but the selected file is for task "' + str ( tmpObj . getName ( ) ) + '". This file was not loaded.' showerror ( message = msg , title = "Error in " + os . path . basename ( fname ) ) self . debug ( msg ) self . debug ( traceback . format_exc ( ) ) return newParList = tmpObj . getParList ( ) try : self . setAllEntriesFromParList ( newParList , updateModel = True ) except editpar . UnfoundParamError as pe : showwarning ( message = str ( pe ) , title = "Error in " + os . path . basename ( fname ) ) self . checkAllTriggers ( 'fopen' ) self . updateTitle ( fname ) self . _taskParsObj . filename = fname self . freshenFocus ( ) self . showStatus ( "Loaded values from: " + fname , keep = 2 ) self . _lastSavedState = self . _taskParsObj . dict ( )
Load the parameter settings from a user - specified file .
4,774
def _handleParListMismatch ( self , probStr , extra = False ) : if extra : return True errmsg = 'Warning: ' if self . _strict : errmsg = 'ERROR: ' errmsg = errmsg + 'mismatch between default and current par lists ' + 'for task "' + self . taskName + '".' if probStr : errmsg += '\n\t' + probStr errmsg += '\nTry editing/deleting: "' + self . _taskParsObj . filename + '" (or, if in PyRAF: "unlearn ' + self . taskName + '").' print ( errmsg ) return True
Override to include ConfigObj filename and specific errors . Note that this only handles missing pars and extra pars not wrong - type pars . So it isn t that big of a deal .
4,775
def _setToDefaults ( self ) : try : tmpObj = cfgpars . ConfigObjPars ( self . _taskParsObj . filename , associatedPkg = self . _taskParsObj . getAssocPkg ( ) , setAllToDefaults = self . taskName , strict = False ) except Exception as ex : msg = "Error Determining Defaults" showerror ( message = msg + '\n\n' + ex . message , title = "Error Determining Defaults" ) return tmpObj . filename = self . _taskParsObj . filename = '' newParList = tmpObj . getParList ( ) try : self . setAllEntriesFromParList ( newParList ) self . checkAllTriggers ( 'defaults' ) self . updateTitle ( '' ) self . showStatus ( "Loaded default " + self . taskName + " values via: " + os . path . basename ( tmpObj . _original_configspec ) , keep = 1 ) except editpar . UnfoundParamError as pe : showerror ( message = str ( pe ) , title = "Error Setting to Default Values" )
Load the default parameter settings into the GUI .
4,776
def getDict ( self ) : badList = self . checkSetSaveEntries ( doSave = False ) if badList : self . processBadEntries ( badList , self . taskName , canCancel = False ) return self . _taskParsObj . dict ( )
Retrieve the current parameter settings from the GUI .
4,777
def loadDict ( self , theDict ) : badList = self . checkSetSaveEntries ( doSave = False ) if badList : if not self . processBadEntries ( badList , self . taskName ) : return cfgpars . mergeConfigObj ( self . _taskParsObj , theDict ) self . _taskParsObj . syncParamList ( False ) try : self . setAllEntriesFromParList ( self . _taskParsObj . getParList ( ) , updateModel = True ) self . checkAllTriggers ( 'fopen' ) self . freshenFocus ( ) self . showStatus ( 'Loaded ' + str ( len ( theDict ) ) + ' user par values for: ' + self . taskName , keep = 1 ) except Exception as ex : showerror ( message = ex . message , title = "Error Setting to Loaded Values" )
Load the parameter settings from a given dict into the GUI .
4,778
def _applyTriggerValue ( self , triggerName , outval ) : depParsDict = self . _taskParsObj . getParsWhoDependOn ( triggerName ) if not depParsDict : return if 0 : print ( "Dependent parameters:\n" + str ( depParsDict ) + "\n" ) theParamList = self . _taskParsObj . getParList ( ) settingMsg = '' for absName in depParsDict : used = False for i in range ( self . numParams ) : scopedName = theParamList [ i ] . scope + '.' + theParamList [ i ] . name if absName == scopedName : depType = depParsDict [ absName ] if depType == 'active_if' : self . entryNo [ i ] . setActiveState ( outval ) elif depType == 'inactive_if' : self . entryNo [ i ] . setActiveState ( not outval ) elif depType == 'is_set_by' : self . entryNo [ i ] . forceValue ( outval , noteEdited = True ) if len ( settingMsg ) > 0 : settingMsg += ", " settingMsg += '"' + theParamList [ i ] . name + '" to "' + outval + '"' elif depType in ( 'set_yes_if' , 'set_no_if' ) : if bool ( outval ) : newval = 'yes' if depType == 'set_no_if' : newval = 'no' self . entryNo [ i ] . forceValue ( newval , noteEdited = True ) if len ( settingMsg ) > 0 : settingMsg += ", " settingMsg += '"' + theParamList [ i ] . name + '" to "' + newval + '"' else : if len ( settingMsg ) > 0 : settingMsg += ", " settingMsg += '"' + theParamList [ i ] . name + '" (no change)' elif depType == 'is_disabled_by' : on = self . entryNo [ i ] . convertToNative ( outval ) if on : self . entryNo [ i ] . setActiveState ( True ) else : self . entryNo [ i ] . forceValue ( outval , noteEdited = True ) self . entryNo [ i ] . setActiveState ( False ) if len ( settingMsg ) > 0 : settingMsg += ", " settingMsg += '"' + theParamList [ i ] . name + '" to "' + outval + '"' else : raise RuntimeError ( 'Unknown dependency: "' + depType + '" for par: "' + scopedName + '"' ) used = True break if absName . endswith ( '._section_' ) : scope = absName [ : - 10 ] depType = depParsDict [ absName ] if depType == 'active_if' : self . _toggleSectionActiveState ( scope , outval , None ) elif depType == 'inactive_if' : self . _toggleSectionActiveState ( scope , not outval , None ) used = True if not used : raise RuntimeError ( 'UNUSED "' + triggerName + '" dependency: ' + str ( { absName : depParsDict [ absName ] } ) ) if len ( settingMsg ) > 0 : self . showStatus ( 'Automatically set ' + settingMsg , keep = 1 )
Here we look through the entire . cfgspc to see if any parameters are affected by this trigger . For those that are we apply the action to the GUI widget . The action is specified by depType .
4,779
def readShiftFile ( self , filename ) : order = [ ] fshift = open ( filename , 'r' ) flines = fshift . readlines ( ) fshift . close ( ) common = [ f . strip ( '#' ) . strip ( ) for f in flines if f . startswith ( '#' ) ] c = [ line . split ( ': ' ) for line in common ] for l in c : if l [ 0 ] not in [ 'frame' , 'refimage' , 'form' , 'units' ] : c . remove ( l ) for line in c : line [ 1 ] = line [ 1 ] . strip ( ) self . update ( c ) files = [ f . strip ( ) . split ( ' ' , 1 ) for f in flines if not ( f . startswith ( '#' ) or f . strip ( ) == '' ) ] for f in files : order . append ( f [ 0 ] ) self [ 'order' ] = order for f in files : if not os . path . exists ( f [ 0 ] ) : f [ 0 ] = fu . buildRootname ( f [ 0 ] ) print ( 'Defining filename in shiftfile as: ' , f [ 0 ] ) f [ 1 ] = f [ 1 ] . split ( ) try : f [ 1 ] = [ float ( s ) for s in f [ 1 ] ] except : msg = 'Cannot read in ' , s , ' from shiftfile ' , filename , ' as a float number' raise ValueError ( msg ) msg = "At least 2 and at most 4 shift values should be provided in a shiftfile" if len ( f [ 1 ] ) < 2 : raise ValueError ( msg ) elif len ( f [ 1 ] ) == 3 : f [ 1 ] . append ( 1.0 ) elif len ( f [ 1 ] ) == 2 : f [ 1 ] . extend ( [ 0.0 , 1.0 ] ) elif len ( f [ 1 ] ) > 4 : raise ValueError ( msg ) fdict = dict ( files ) self . update ( fdict )
Reads a shift file from disk and populates a dictionary .
4,780
def writeShiftFile ( self , filename = "shifts.txt" ) : lines = [ '# frame: ' , self [ 'frame' ] , '\n' , '# refimage: ' , self [ 'refimage' ] , '\n' , '# form: ' , self [ 'form' ] , '\n' , '# units: ' , self [ 'units' ] , '\n' ] for o in self [ 'order' ] : ss = " " for shift in self [ o ] : ss += str ( shift ) + " " line = str ( o ) + ss + "\n" lines . append ( line ) fshifts = open ( filename , 'w' ) fshifts . writelines ( lines ) fshifts . close ( )
Writes a shift file object to a file on disk using the convention for shift file format .
4,781
def weave_instance ( instance , aspect , methods = NORMAL_METHODS , lazy = False , bag = BrokenBag , ** options ) : if bag . has ( instance ) : return Nothing entanglement = Rollback ( ) method_matches = make_method_matcher ( methods ) logdebug ( "weave_instance (module=%r, aspect=%s, methods=%s, lazy=%s, **options=%s)" , instance , aspect , methods , lazy , options ) def fixup ( func ) : return func . __get__ ( instance , type ( instance ) ) fixed_aspect = aspect + [ fixup ] if isinstance ( aspect , ( list , tuple ) ) else [ aspect , fixup ] for attr in dir ( instance ) : func = getattr ( instance , attr ) if method_matches ( attr ) : if ismethod ( func ) : if hasattr ( func , '__func__' ) : realfunc = func . __func__ else : realfunc = func . im_func entanglement . merge ( patch_module ( instance , attr , _checked_apply ( fixed_aspect , realfunc , module = None ) , ** options ) ) return entanglement
Low - level weaver for instances .
4,782
def weave_module ( module , aspect , methods = NORMAL_METHODS , lazy = False , bag = BrokenBag , ** options ) : if bag . has ( module ) : return Nothing entanglement = Rollback ( ) method_matches = make_method_matcher ( methods ) logdebug ( "weave_module (module=%r, aspect=%s, methods=%s, lazy=%s, **options=%s)" , module , aspect , methods , lazy , options ) for attr in dir ( module ) : func = getattr ( module , attr ) if method_matches ( attr ) : if isroutine ( func ) : entanglement . merge ( patch_module_function ( module , func , aspect , force_name = attr , ** options ) ) elif isclass ( func ) : entanglement . merge ( weave_class ( func , aspect , owner = module , name = attr , methods = methods , lazy = lazy , bag = bag , ** options ) , ) return entanglement
Low - level weaver for whole module weaving .
4,783
def patch_module ( module , name , replacement , original = UNSPECIFIED , aliases = True , location = None , ** _bogus_options ) : rollback = Rollback ( ) seen = False original = getattr ( module , name ) if original is UNSPECIFIED else original location = module . __name__ if hasattr ( module , '__name__' ) else type ( module ) . __module__ target = module . __name__ if hasattr ( module , '__name__' ) else type ( module ) . __name__ try : replacement . __module__ = location except ( TypeError , AttributeError ) : pass for alias in dir ( module ) : logdebug ( "alias:%s (%s)" , alias , name ) if hasattr ( module , alias ) : obj = getattr ( module , alias ) logdebug ( "- %s:%s (%s)" , obj , original , obj is original ) if obj is original : if aliases or alias == name : logdebug ( "= saving %s on %s.%s ..." , replacement , target , alias ) setattr ( module , alias , replacement ) rollback . merge ( lambda alias = alias : setattr ( module , alias , original ) ) if alias == name : seen = True elif alias == name : if ismethod ( obj ) : logdebug ( "= saving %s on %s.%s ..." , replacement , target , alias ) setattr ( module , alias , replacement ) rollback . merge ( lambda alias = alias : setattr ( module , alias , original ) ) seen = True else : raise AssertionError ( "%s.%s = %s is not %s." % ( module , alias , obj , original ) ) if not seen : warnings . warn ( 'Setting %s.%s to %s. There was no previous definition, probably patching the wrong module.' % ( target , name , replacement ) ) logdebug ( "= saving %s on %s.%s ..." , replacement , target , name ) setattr ( module , name , replacement ) rollback . merge ( lambda : setattr ( module , name , original ) ) return rollback
Low - level attribute patcher .
4,784
def patch_module_function ( module , target , aspect , force_name = None , bag = BrokenBag , ** options ) : logdebug ( "patch_module_function (module=%s, target=%s, aspect=%s, force_name=%s, **options=%s" , module , target , aspect , force_name , options ) name = force_name or target . __name__ return patch_module ( module , name , _checked_apply ( aspect , target , module = module ) , original = target , ** options )
Low - level patcher for one function from a specified module .
4,785
def unstuff ( packet ) : if is_framed ( packet ) : raise ValueError ( 'packet contains leading DLE and trailing DLE/ETX' ) else : return packet . replace ( CHR_DLE + CHR_DLE , CHR_DLE )
Remove byte stuffing from a TSIP packet .
4,786
def open ( self ) : if self . handle is None : self . handle = fits . open ( self . fname , mode = 'readonly' ) if self . extn : if len ( self . extn ) == 1 : hdu = self . handle [ self . extn [ 0 ] ] else : hdu = self . handle [ self . extn [ 0 ] , self . extn [ 1 ] ] else : hdu = self . handle [ 0 ] if isinstance ( hdu , fits . hdu . compressed . CompImageHDU ) : self . compress = True return hdu
Opens the file for subsequent access .
4,787
def reloadCompletedMeasurements ( self ) : from pathlib import Path reloaded = [ self . load ( x . resolve ( ) ) for x in Path ( self . dataDir ) . glob ( '*/*/*' ) if x . is_dir ( ) ] logger . info ( 'Reloaded ' + str ( len ( reloaded ) ) + ' completed measurements' ) self . completeMeasurements = [ x for x in reloaded if x is not None and x . status == MeasurementStatus . COMPLETE ] self . failedMeasurements = [ x for x in reloaded if x is not None and x . status == MeasurementStatus . FAILED ]
Reloads the completed measurements from the backing store .
4,788
def check_exptime ( filelist ) : toclose = False removed_files = [ ] for f in filelist : if isinstance ( f , str ) : f = fits . open ( f ) toclose = True try : exptime = f [ 0 ] . header [ 'EXPTIME' ] except KeyError : removed_files . append ( f ) print ( "Warning: There are files without keyword EXPTIME" ) continue if exptime <= 0 : removed_files . append ( f ) print ( "Warning: There are files with zero exposure time: keyword EXPTIME = 0.0" ) if removed_files != [ ] : print ( "Warning: Removing the following files from input list" ) for f in removed_files : print ( '\t' , f . filename ( ) or "" ) return removed_files
Removes files with EXPTIME == 0 from filelist .
4,789
def convert2fits ( sci_ivm ) : removed_files = [ ] translated_names = [ ] newivmlist = [ ] for file in sci_ivm : try : imgfits , imgtype = fileutil . isFits ( file [ 0 ] ) except IOError : print ( "Warning: File %s could not be found" % file [ 0 ] ) print ( "Warning: Removing file %s from input list" % file [ 0 ] ) removed_files . append ( file [ 0 ] ) continue if imgfits and imgtype == 'waiver' : newfilename = waiver2mef ( file [ 0 ] , convert_dq = True ) if newfilename is None : print ( "Removing file %s from input list - could not convert WAIVER format to MEF\n" % file [ 0 ] ) removed_files . append ( file [ 0 ] ) else : removed_files . append ( file [ 0 ] ) translated_names . append ( newfilename ) newivmlist . append ( file [ 1 ] ) if not imgfits : newfilename = geis2mef ( file [ 0 ] , convert_dq = True ) if newfilename is None : print ( "Removing file %s from input list - could not convert GEIS format to MEF\n" % file [ 0 ] ) removed_files . append ( file [ 0 ] ) else : removed_files . append ( file [ 0 ] ) translated_names . append ( newfilename ) newivmlist . append ( file [ 1 ] ) return removed_files , translated_names , newivmlist
Checks if a file is in WAIVER of GEIS format and converts it to MEF
4,790
def journals ( self ) : try : target = self . _item_path json_data = self . _redmine . get ( target % str ( self . id ) , parms = { 'include' : 'journals' } ) data = self . _redmine . unwrap_json ( None , json_data ) journals = [ Journal ( redmine = self . _redmine , data = journal , type = 'issue_journal' ) for journal in data [ 'issue' ] [ 'journals' ] ] return journals except Exception : return [ ]
Retrieve journals attribute for this very Issue
4,791
def save ( self , notes = None ) : if notes : self . _changes [ 'notes' ] = notes super ( Issue , self ) . save ( )
Save all changes back to Redmine with optional notes .
4,792
def set_status ( self , new_status , notes = None ) : self . status_id = new_status try : self . status [ 'id' ] = self . status_id self . status [ 'name' ] = None except : pass self . save ( notes )
Save all changes and set to the given new_status
4,793
def resolve ( self , notes = None ) : self . set_status ( self . _redmine . ISSUE_STATUS_ID_RESOLVED , notes = notes )
Save all changes and resolve this issue
4,794
def close ( self , notes = None ) : self . set_status ( self . _redmine . ISSUE_STATUS_ID_CLOSED , notes = notes )
Save all changes and close this issue
4,795
def new ( self , page_name , ** dict ) : self . _item_new_path = '/projects/%s/wiki/%s.json' % ( self . _project . identifier , page_name ) return super ( Redmine_Wiki_Pages_Manager , self ) . new ( ** dict )
Create a new item with the provided dict information at the given page_name . Returns the new item .
4,796
def _set_version ( self , version ) : self . version = version or None version_check = version or 9999.0 if version_check < 1.0 : raise RedmineError ( 'This library will only work with ' 'Redmine version 1.0 and higher.' ) self . key_in_header = version >= 1.1 self . impersonation_supported = version_check >= 2.2 self . has_project_memberships = version_check >= 1.4 self . has_project_versions = version_check >= 1.3 self . has_wiki_pages = version_check >= 2.2 for manager_version in self . _item_managers_by_version : if version_check >= manager_version : managers = self . _item_managers_by_version [ manager_version ] for attribute_name , item in managers . iteritems ( ) : setattr ( self , attribute_name , Redmine_Items_Manager ( self , item ) )
Set up this object based on the capabilities of the known versions of Redmine
4,797
def interpret_bits_value ( val ) : if isinstance ( val , int ) or val is None : return val else : val = str ( val ) . strip ( ) if val . startswith ( '~' ) : flip_bits = True val = val [ 1 : ] . lstrip ( ) else : flip_bits = False if val . startswith ( '(' ) : if val . endswith ( ')' ) : val = val [ 1 : - 1 ] . strip ( ) else : raise ValueError ( 'Unbalanced parantheses or incorrect syntax.' ) if ',' in val : valspl = val . split ( ',' ) bitmask = 0 for v in valspl : bitmask += int ( v ) elif '+' in val : valspl = val . split ( '+' ) bitmask = 0 for v in valspl : bitmask += int ( v ) elif val . upper ( ) in [ '' , 'NONE' , 'INDEF' ] : return None else : bitmask = int ( val ) if flip_bits : bitmask = ~ bitmask return bitmask
Converts input bits value from string to a single integer value or None . If a comma - or + - separated set of values are provided they are summed .
4,798
def output_influx ( data ) : for contract in data : yesterday_data = data [ contract ] [ 'yesterday_hourly_consumption' ] del data [ contract ] [ 'yesterday_hourly_consumption' ] out = "pyhydroquebec,contract=" + contract + " " for index , key in enumerate ( data [ contract ] ) : if index != 0 : out = out + "," if key in ( "annual_date_start" , "annual_date_end" ) : out += key + "=\"" + str ( data [ contract ] [ key ] ) + "\"" else : out += key + "=" + str ( data [ contract ] [ key ] ) out += " " + str ( int ( datetime . datetime . now ( HQ_TIMEZONE ) . timestamp ( ) * 1000000000 ) ) print ( out ) yesterday = datetime . datetime . now ( HQ_TIMEZONE ) - datetime . timedelta ( days = 1 ) yesterday = yesterday . replace ( minute = 0 , hour = 0 , second = 0 , microsecond = 0 ) for hour in yesterday_data : msg = "pyhydroquebec,contract={} {} {}" data = "," . join ( [ "{}={}" . format ( key , value ) for key , value in hour . items ( ) if key != 'hour' ] ) datatime = datetime . datetime . strptime ( hour [ 'hour' ] , '%H:%M:%S' ) yesterday = yesterday . replace ( hour = datatime . hour ) yesterday_str = str ( int ( yesterday . timestamp ( ) * 1000000000 ) ) print ( msg . format ( contract , data , yesterday_str ) )
Print data using influxDB format .
4,799
def to_jd ( year , month , day ) : gy = year - 1 + EPOCH_GREGORIAN_YEAR if month != 20 : m = 0 else : if isleap ( gy + 1 ) : m = - 14 else : m = - 15 return gregorian . to_jd ( gy , 3 , 20 ) + ( 19 * ( month - 1 ) ) + m + day
Determine Julian day from Bahai date