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 ( ... | 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 , ... | 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 ( * arg... | 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... | 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 , ) ) recyc... | 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 ] ... | 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... | 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 er... | 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 .... | 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 . obj... | 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 ( 'Unfo... | 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 Excep... | 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... |
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 = [ ... | 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" me... | 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" +... | 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 . get... | 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: %... | 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 Vd... | 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 < m... | 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 , val... | 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... | 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 ... | 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 )... | 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... | 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:" ) o... | 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 ... | 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 e... | 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 . _showHelpInBrows... | 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 . getF... | 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 : i... | 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' envVarNa... | 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 ... | 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" , se... | 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/... | 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 . mess... | 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 ( s... | 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 depParsDi... | 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' , 'refima... | 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 ) + " " l... | 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)... | 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)" , modu... | 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 ... | 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 ( mo... | 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 ( h... | 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 reloade... | 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 i... | 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 ] ) r... | 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 journa... | 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 ... | 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 (... | 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 ... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.