idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
4,800
def from_jd ( jd ) : jd = trunc ( jd ) + 0.5 g = gregorian . from_jd ( jd ) gy = g [ 0 ] bstarty = EPOCH_GREGORIAN_YEAR if jd <= gregorian . to_jd ( gy , 3 , 20 ) : x = 1 else : x = 0 bys = gy - ( bstarty + ( ( ( gregorian . to_jd ( gy , 1 , 1 ) <= jd ) and x ) ) ) year = bys + 1 days = jd - to_jd ( year , 1 , 1 ) bld ...
Calculate Bahai date from Julian day
4,801
def to_jd ( baktun , katun , tun , uinal , kin ) : return EPOCH + ( baktun * 144000 ) + ( katun * 7200 ) + ( tun * 360 ) + ( uinal * 20 ) + kin
Determine Julian day from Mayan long count
4,802
def from_jd ( jd ) : d = jd - EPOCH baktun = trunc ( d / 144000 ) d = ( d % 144000 ) katun = trunc ( d / 7200 ) d = ( d % 7200 ) tun = trunc ( d / 360 ) d = ( d % 360 ) uinal = trunc ( d / 20 ) kin = int ( ( d % 20 ) ) return ( baktun , katun , tun , uinal , kin )
Calculate Mayan long count from Julian day
4,803
def to_haab ( jd ) : lcount = trunc ( jd ) + 0.5 - EPOCH day = ( lcount + 348 ) % 365 count = day % 20 month = trunc ( day / 20 ) return int ( count ) , HAAB_MONTHS [ month ]
Determine Mayan Haab month and day from Julian day
4,804
def to_tzolkin ( jd ) : lcount = trunc ( jd ) + 0.5 - EPOCH day = amod ( lcount + 4 , 13 ) name = amod ( lcount + 20 , 20 ) return int ( day ) , TZOLKIN_NAMES [ int ( name ) - 1 ]
Determine Mayan Tzolkin month and day from Julian day
4,805
def longcount_generator ( baktun , katun , tun , uinal , kin ) : j = to_jd ( baktun , katun , tun , uinal , kin ) while True : yield from_jd ( j ) j = j + 1
Generate long counts starting with input
4,806
def next_haab ( month , jd ) : if jd < EPOCH : raise IndexError ( "Input day is before Mayan epoch." ) hday , hmonth = to_haab ( jd ) if hmonth == month : days = 1 - hday else : count1 = _haab_count ( hday , hmonth ) count2 = _haab_count ( 1 , month ) days = ( count2 - count1 ) % 365 return jd + days
For a given haab month and a julian day count find the next start of that month on or after the JDC
4,807
def next_tzolkin ( tzolkin , jd ) : if jd < EPOCH : raise IndexError ( "Input day is before Mayan epoch." ) count1 = _tzolkin_count ( * to_tzolkin ( jd ) ) count2 = _tzolkin_count ( * tzolkin ) add_days = ( count2 - count1 ) % 260 return jd + add_days
For a given tzolk in day and a julian day count find the next occurrance of that tzolk in after the date
4,808
def next_tzolkin_haab ( tzolkin , haab , jd ) : haabcount = _haab_count ( * to_haab ( jd ) ) haab_desired_count = _haab_count ( * haab ) haab_days = ( haab_desired_count - haabcount ) % 365 possible_haab = set ( h + haab_days for h in range ( 0 , 18980 , 365 ) ) tzcount = _tzolkin_count ( * to_tzolkin ( jd ) ) tz_desir...
For a given haab - tzolk in combination and a Julian day count find the next occurrance of the combination after the date
4,809
def haab_monthcalendar ( baktun = None , katun = None , tun = None , uinal = None , kin = None , jdc = None ) : if not jdc : jdc = to_jd ( baktun , katun , tun , uinal , kin ) haab_number , haab_month = to_haab ( jdc ) first_j = jdc - haab_number + 1 tzolkin_start_number , tzolkin_start_name = to_tzolkin ( first_j ) ge...
For a given long count return a calender of the current haab month divided into tzolkin weeks
4,810
def _update_data ( self , data = { } ) : pending_changes = self . _changes or { } try : del self . _changes except : pass try : custom_field_data = data . pop ( 'custom_fields' ) except KeyError : pass else : self . custom_fields = Custom_Fields ( custom_field_data ) for key , value in data . iteritems ( ) : lookup_key...
Update the data in this object .
4,811
def _remap_tag_to_tag_id ( cls , tag , new_data ) : try : value = new_data [ tag ] except : return tag_id = tag + '_id' try : new_data [ tag_id ] = value [ 'id' ] except : try : new_data [ tag_id ] = value . id except AttributeError : new_data [ tag_id ] = value del new_data [ tag ]
Remaps a given changed field from tag to tag_id .
4,812
def _add_item_manager ( self , key , item_class , ** paths ) : updated_paths = { } for path_type , path_value in paths . iteritems ( ) : updated_paths [ path_type ] = path_value . format ( ** self . __dict__ ) manager = Redmine_Items_Manager ( self . _redmine , item_class , ** updated_paths ) self . __dict__ [ key ] = ...
Add an item manager to this object .
4,813
def refresh ( self ) : if not self . _item_path : raise AttributeError ( 'refresh is not available for %s' % self . _type ) if not self . id : raise RedmineError ( '%s did not come from the Redmine server - no link.' % self . _type ) try : self . save ( ) except : pass target = self . _item_path % self . id json_data =...
Refresh this item from data on the server . Will save any unsaved data first .
4,814
def _get_changes ( self ) : result = dict ( ( f [ 'id' ] , f . get ( 'value' , '' ) ) for f in self . _data if f . get ( 'changed' , False ) ) self . _clear_changes return result
Get all changed values .
4,815
def new ( self , ** dict ) : if not self . _item_new_path : raise AttributeError ( 'new is not available for %s' % self . _item_name ) for tag in self . _object . _remap_to_id : self . _object . _remap_tag_to_tag_id ( tag , dict ) target = self . _item_new_path payload = json . dumps ( { self . _item_type : dict } ) js...
Create a new item with the provided dict information . Returns the new item .
4,816
def get ( self , id , ** options ) : if not self . _item_path : raise AttributeError ( 'get is not available for %s' % self . _item_name ) target = self . _item_path % id json_data = self . _redmine . get ( target , ** options ) data = self . _redmine . unwrap_json ( self . _item_type , json_data ) data [ '_source_path...
Get a single item with the given ID
4,817
def update ( self , id , ** dict ) : if not self . _item_path : raise AttributeError ( 'update is not available for %s' % self . _item_name ) target = ( self . _update_path or self . _item_path ) % id payload = json . dumps ( { self . _item_type : dict } ) self . _redmine . put ( target , payload ) return None
Update a given item with the passed data .
4,818
def delete ( self , id ) : if not self . _item_path : raise AttributeError ( 'delete is not available for %s' % self . _item_name ) target = self . _item_path % id self . _redmine . delete ( target ) return None
Delete a single item with the given ID
4,819
def query ( self , ** options ) : if not self . _query_path : raise AttributeError ( 'query is not available for %s' % self . _item_name ) last_item = 0 offset = 0 current_item = None limit = options . get ( 'limit' , 25 ) options [ 'limit' ] = limit target = self . _query_path while True : options [ 'offset' ] = offse...
Return an iterator for the given items .
4,820
def _setup_authentication ( self , username , password ) : if self . version < 1.1 : if not username : username = self . _key self . _key = None if not username : return if not password : password = '12345' password_mgr = urllib2 . HTTPPasswordMgrWithDefaultRealm ( ) password_mgr . add_password ( None , self . _url , u...
Create the authentication object with the given credentials .
4,821
def open_raw ( self , page , parms = None , payload = None , HTTPrequest = None , payload_type = 'application/json' ) : if not parms : parms = { } if self . _key and not self . key_in_header : parms [ 'key' ] = self . _key urldata = '' if parms : urldata = '?' + urllib . urlencode ( parms ) fullUrl = self . _url + page...
Opens a page from the server with optional XML . Returns a response file - like object
4,822
def open ( self , page , parms = None , payload = None , HTTPrequest = None ) : response = self . open_raw ( page , parms , payload , HTTPrequest ) return response . read ( )
Opens a page from the server with optional content . Returns the string response .
4,823
def post ( self , page , payload , parms = None ) : if self . readonlytest : print 'Redmine read only test: Pretending to create: ' + page return payload else : return self . open ( page , parms , payload )
Posts a string payload to the server - used to make new Redmine items . Returns an JSON string or error .
4,824
def put ( self , page , payload , parms = None ) : if self . readonlytest : print 'Redmine read only test: Pretending to update: ' + page else : return self . open ( page , parms , payload , HTTPrequest = self . PUT_Request )
Puts an XML object on the server - used to update Redmine items . Returns nothing useful .
4,825
def delete ( self , page ) : if self . readonlytest : print 'Redmine read only test: Pretending to delete: ' + page else : return self . open ( page , HTTPrequest = self . DELETE_Request )
Deletes a given object on the server - used to remove items from Redmine . Use carefully!
4,826
def unwrap_json ( self , type , json_data ) : try : data = json . loads ( json_data ) except ValueError : raise RedmineError ( json_data ) try : data = data [ type ] except KeyError : pass return data
Decodes a json string and unwraps any type it finds within .
4,827
def find_all_item_classes ( self ) : import redmine as public_classes item_class = { } for key , value in public_classes . __dict__ . items ( ) : try : if issubclass ( value , Redmine_Item ) : item_class [ key . lower ( ) ] = value except : continue self . item_class = item_class
Finds and stores a reference to all Redmine_Item subclasses for later use .
4,828
def check_cache ( self , type , data , obj = None ) : try : id = data [ 'id' ] except : return data try : type = obj . _get_type ( ) except : pass try : hit = self . item_cache [ type ] [ id ] except KeyError : pass else : hit . _update_data ( data ) return hit if not obj : obj = self . item_class . get ( type , Redmin...
Returns the updated cached version of the given dict
4,829
def substract ( self , pt ) : if isinstance ( pt , Point ) : return Point ( pt . x - self . x , pt . y - self . y , pt . z - self . z ) else : raise TypeError
Return a Point instance as the displacement of two points .
4,830
def from_list ( cls , l ) : if len ( l ) == 3 : x , y , z = map ( float , l ) return cls ( x , y , z ) elif len ( l ) == 2 : x , y = map ( float , l ) return cls ( x , y ) else : raise AttributeError
Return a Point instance from a given list
4,831
def multiply ( self , number ) : return self . from_list ( [ x * number for x in self . to_list ( ) ] )
Return a Vector as the product of the vector and a real number .
4,832
def magnitude ( self ) : return math . sqrt ( reduce ( lambda x , y : x + y , [ x ** 2 for x in self . to_list ( ) ] ) )
Return magnitude of the vector .
4,833
def sum ( self , vector ) : return self . from_list ( [ x + vector . vector [ i ] for i , x in self . to_list ( ) ] )
Return a Vector instance as the vector sum of two vectors .
4,834
def dot ( self , vector , theta = None ) : if theta is not None : return ( self . magnitude ( ) * vector . magnitude ( ) * math . degrees ( math . cos ( theta ) ) ) return ( reduce ( lambda x , y : x + y , [ x * vector . vector [ i ] for i , x in self . to_list ( ) ( ) ] ) )
Return the dot product of two vectors .
4,835
def cross ( self , vector ) : return Vector ( ( self . y * vector . z - self . z * vector . y ) , ( self . z * vector . x - self . x * vector . z ) , ( self . x * vector . y - self . y * vector . x ) )
Return a Vector instance as the cross product of two vectors
4,836
def unit ( self ) : return Vector ( ( self . x / self . magnitude ( ) ) , ( self . y / self . magnitude ( ) ) , ( self . z / self . magnitude ( ) ) )
Return a Vector instance of the unit vector
4,837
def angle ( self , vector ) : return math . degrees ( math . acos ( self . dot ( vector ) / ( self . magnitude ( ) * vector . magnitude ( ) ) ) )
Return the angle between two vectors in degrees .
4,838
def non_parallel ( self , vector ) : if ( self . is_parallel ( vector ) is not True and self . is_perpendicular ( vector ) is not True ) : return True return False
Return True if vectors are non - parallel .
4,839
def rotate ( self , angle , axis = ( 0 , 0 , 1 ) ) : if not all ( isinstance ( a , int ) for a in axis ) : raise ValueError x , y , z = self . x , self . y , self . z if ( axis [ 2 ] ) : x = ( self . x * math . cos ( angle ) - self . y * math . sin ( angle ) ) y = ( self . x * math . sin ( angle ) + self . y * math . c...
Returns the rotated vector . Assumes angle is in radians
4,840
def from_points ( cls , point1 , point2 ) : if isinstance ( point1 , Point ) and isinstance ( point2 , Point ) : displacement = point1 . substract ( point2 ) return cls ( displacement . x , displacement . y , displacement . z ) raise TypeError
Return a Vector instance from two given points .
4,841
def spherical ( cls , mag , theta , phi = 0 ) : return cls ( mag * math . sin ( phi ) * math . cos ( theta ) , mag * math . sin ( phi ) * math . sin ( theta ) , mag * math . cos ( phi ) )
Returns a Vector instance from spherical coordinates
4,842
def cylindrical ( cls , mag , theta , z = 0 ) : return cls ( mag * math . cos ( theta ) , mag * math . sin ( theta ) , z )
Returns a Vector instance from cylindircal coordinates
4,843
def amod ( a , b ) : modded = int ( a % b ) return b if modded is 0 else modded
Modulus function which returns numerator if modulus is zero
4,844
def search_weekday ( weekday , jd , direction , offset ) : return weekday_before ( weekday , jd + ( direction * offset ) )
Determine the Julian date for the next or previous weekday
4,845
def irafglob ( inlist , atfile = None ) : if inlist is None or len ( inlist ) == 0 : return [ ] if isinstance ( inlist , list ) : flist = [ ] for f in inlist : flist += irafglob ( f ) elif ',' in inlist : flist = [ ] for f in inlist . split ( ',' ) : f = f . strip ( ) flist += irafglob ( f ) elif inlist [ 0 ] == '@' : ...
Returns a list of filenames based on the type of IRAF input .
4,846
def pack ( self ) : try : structs_ = get_structs_for_fields ( [ self . fields [ 0 ] ] ) except ( TypeError ) : raise PackError ( self ) if structs_ == [ ] : try : structs_ = get_structs_for_fields ( [ self . fields [ 0 ] , self . fields [ 1 ] ] ) except ( IndexError , TypeError ) : raise PackError ( self ) for struct_ ...
Return binary format of packet .
4,847
def unpack ( cls , rawpacket ) : structs_ = get_structs_for_rawpacket ( rawpacket ) for struct_ in structs_ : try : return cls ( * struct_ . unpack ( rawpacket ) ) except struct . error : raise pass return cls ( 0xff , rawpacket )
Instantiate Packet from binary string .
4,848
def ch_handler ( offset = 0 , length = - 1 , ** kw ) : global _lastSel offset = int ( offset ) length = int ( length ) if length < 0 : length = len ( _lastSel ) return _lastSel [ offset : offset + length ]
Handle standard PRIMARY clipboard access . Note that offset and length are passed as strings . This differs from CLIPBOARD .
4,849
def put ( text , cbname ) : global _lastSel _checkTkInit ( ) if cbname == 'CLIPBOARD' : _theRoot . clipboard_clear ( ) if text : _theRoot . clipboard_append ( text ) return if cbname == 'PRIMARY' : _lastSel = text _theRoot . selection_handle ( ch_handler , selection = 'PRIMARY' ) _theRoot . selection_own ( selection = ...
Put the given string into the given clipboard .
4,850
def get ( cbname ) : _checkTkInit ( ) if cbname == 'PRIMARY' : try : return _theRoot . selection_get ( selection = 'PRIMARY' ) except : return None if cbname == 'CLIPBOARD' : try : return _theRoot . selection_get ( selection = 'CLIPBOARD' ) except : return None raise RuntimeError ( "Unexpected clipboard name: " + str (...
Get the contents of the given clipboard .
4,851
def put ( self , measurementId ) : json = request . get_json ( ) try : start = self . _calculateStartTime ( json ) except ValueError : return 'invalid date format in request' , 400 duration = json [ 'duration' ] if 'duration' in json else 10 if start is None : return 'no start time' , 400 else : scheduled , message = s...
Initiates a new measurement . Accepts a json payload with the following attributes ;
4,852
def printCols ( strlist , cols = 5 , width = 80 ) : nlines = ( len ( strlist ) + cols - 1 ) // cols line = nlines * [ "" ] for i in range ( len ( strlist ) ) : c , r = divmod ( i , nlines ) nwid = c * width // cols - len ( line [ r ] ) if nwid > 0 : line [ r ] = line [ r ] + nwid * " " + strlist [ i ] else : line [ r ]...
Print elements of list in cols columns
4,853
def stripQuotes ( value ) : if value [ : 1 ] == '"' : value = value [ 1 : ] if value [ - 1 : ] == '"' : value = value [ : - 1 ] value = re . sub ( _re_doubleq2 , '"' , value ) elif value [ : 1 ] == "'" : value = value [ 1 : ] if value [ - 1 : ] == "'" : value = value [ : - 1 ] value = re . sub ( _re_singleq2 , "'" , va...
Strip single or double quotes off string ; remove embedded quote pairs
4,854
def rglob ( root , pattern ) : retlist = [ ] if None not in ( pattern , root ) : for base , dirs , files in os . walk ( root ) : goodfiles = fnmatch . filter ( files , pattern ) retlist . extend ( os . path . join ( base , f ) for f in goodfiles ) return retlist
Same thing as glob . glob but recursively checks subdirs .
4,855
def translateName ( s , dot = 0 ) : s = s . replace ( '$' , 'DOLLAR' ) sparts = s . split ( '.' ) for i in range ( len ( sparts ) ) : if sparts [ i ] == "" or sparts [ i ] [ 0 ] in string . digits or keyword . iskeyword ( sparts [ i ] ) : sparts [ i ] = 'PY' + sparts [ i ] if dot : return 'DOT' . join ( sparts ) else :...
Convert CL parameter or variable name to Python - acceptable name
4,856
def init_tk_default_root ( withdraw = True ) : if not capable . OF_GRAPHICS : raise RuntimeError ( "Cannot run this command without graphics" ) if not TKNTR . _default_root : junk = TKNTR . Tk ( ) retval = TKNTR . _default_root if withdraw and retval : retval . withdraw ( ) return retval
In case the _default_root value is required you may safely call this ahead of time to ensure that it has been initialized . If it has already been this is a no - op .
4,857
def tkreadline ( file = None ) : if file is None : file = sys . stdin if not hasattr ( file , "readline" ) : raise TypeError ( "file must be a filehandle with a readline method" ) try : fd = file . fileno ( ) except : fd = None if ( fd and capable . OF_GRAPHICS ) : tkread ( fd , 0 ) if not select . select ( [ fd ] , [ ...
Read a line from file while running Tk mainloop .
4,858
def launchBrowser ( url , brow_bin = 'mozilla' , subj = None ) : if not subj : subj = url if sys . platform not in ( 'os2warp, iphone' ) : import webbrowser if not webbrowser . open ( url ) : print ( "Error opening URL: " + url ) else : print ( 'Help on "' + subj + '" is now being displayed in a web browser' ) return p...
Given a URL try to pop it up in a browser on most platforms . brow_bin is only used on OS s where there is no open or start cmd .
4,859
def read ( self , file , nbytes ) : if not capable . OF_GRAPHICS : raise RuntimeError ( "Cannot run this command without graphics" ) if isinstance ( file , int ) : fd = file else : try : fd = file . fileno ( ) except : raise TypeError ( "file must be an integer or a filehandle/socket" ) init_tk_default_root ( ) self . ...
Read nbytes characters from file while running Tk mainloop
4,860
def _read ( self , fd , mask ) : try : if select . select ( [ fd ] , [ ] , [ ] , 0 ) [ 0 ] : snew = os . read ( fd , self . nbytes ) if PY3K : snew = snew . decode ( 'ascii' , 'replace' ) self . value . append ( snew ) self . nbytes -= len ( snew ) else : snew = '' if ( self . nbytes <= 0 or len ( snew ) == 0 ) and sel...
Read waiting data and terminate Tk mainloop if done
4,861
def legal_date ( year , month , day ) : try : assert year >= 1 assert 0 < month <= 14 assert 0 < day <= 28 if month == 14 : if isleap ( year + YEAR_EPOCH - 1 ) : assert day <= 2 else : assert day == 1 except AssertionError : raise ValueError ( "Invalid Positivist date: ({}, {}, {})" . format ( year , month , day ) ) re...
Checks if a given date is a legal positivist date
4,862
def to_jd ( year , month , day ) : legal_date ( year , month , day ) gyear = year + YEAR_EPOCH - 1 return ( gregorian . EPOCH - 1 + ( 365 * ( gyear - 1 ) ) + floor ( ( gyear - 1 ) / 4 ) + ( - floor ( ( gyear - 1 ) / 100 ) ) + floor ( ( gyear - 1 ) / 400 ) + ( month - 1 ) * 28 + day )
Convert a Positivist date to Julian day count .
4,863
def from_jd ( jd ) : try : assert jd >= EPOCH except AssertionError : raise ValueError ( 'Invalid Julian day' ) depoch = floor ( jd - 0.5 ) + 0.5 - gregorian . EPOCH quadricent = floor ( depoch / gregorian . INTERCALATION_CYCLE_DAYS ) dqc = depoch % gregorian . INTERCALATION_CYCLE_DAYS cent = floor ( dqc / gregorian . ...
Convert a Julian day count to Positivist date .
4,864
def dayname ( year , month , day ) : legal_date ( year , month , day ) yearday = ( month - 1 ) * 28 + day if isleap ( year + YEAR_EPOCH - 1 ) : dname = data . day_names_leap [ yearday - 1 ] else : dname = data . day_names [ yearday - 1 ] return MONTHS [ month - 1 ] , dname
Give the name of the month and day for a given date .
4,865
def _evictStaleDevices ( self ) : while self . running : expiredDeviceIds = [ key for key , value in self . devices . items ( ) if value . hasExpired ( ) ] for key in expiredDeviceIds : logger . warning ( "Device timeout, removing " + key ) del self . devices [ key ] time . sleep ( 1 ) logger . warning ( "DeviceCaretak...
A housekeeping function which runs in a worker thread and which evicts devices that haven t sent an update for a while .
4,866
def list_parse ( name_list ) : if name_list and name_list [ 0 ] == '@' : value = name_list [ 1 : ] if not os . path . exists ( value ) : log . warning ( 'The file %s does not exist' % value ) return try : return [ v . strip ( ) for v in open ( value , 'r' ) . readlines ( ) ] except IOError as e : log . warning ( 'readi...
Parse a comma - separated list of values or a filename ( starting with
4,867
def _mmInit ( self ) : mmkeys = { } mmkeysGet = mmkeys . setdefault minkeylength = self . minkeylength for key in self . data . keys ( ) : lenkey = len ( key ) start = min ( minkeylength , lenkey ) for i in range ( start , lenkey + 1 ) : mmkeysGet ( key [ 0 : i ] , [ ] ) . append ( key ) self . mmkeys = mmkeys
Create the minimum match dictionary of keys
4,868
def resolve ( self , key , keylist ) : raise AmbiguousKeyError ( "Ambiguous key " + repr ( key ) + ", could be any of " + str ( sorted ( keylist ) ) )
Hook to resolve ambiguities in selected keys
4,869
def get ( self , key , failobj = None , exact = 0 ) : if not exact : key = self . getfullkey ( key , new = 1 ) return self . data . get ( key , failobj )
Raises exception if key is ambiguous
4,870
def _has ( self , key , exact = 0 ) : if not exact : key = self . getfullkey ( key , new = 1 ) return key in self . data
Raises an exception if key is ambiguous
4,871
def getall ( self , key , failobj = None ) : if self . mmkeys is None : self . _mmInit ( ) k = self . mmkeys . get ( key ) if not k : return failobj return list ( map ( self . data . get , k ) )
Returns a list of all the matching values for key containing a single entry for unambiguous matches and multiple entries for ambiguous matches .
4,872
def get ( self , key , failobj = None , exact = 0 ) : if not exact : try : key = self . getfullkey ( key ) except KeyError : return failobj return self . data . get ( key , failobj )
Returns failobj if key is not found or is ambiguous
4,873
def _has ( self , key , exact = 0 ) : if not exact : try : key = self . getfullkey ( key ) return 1 except KeyError : return 0 else : return key in self . data
Returns false if key is not found or is ambiguous
4,874
def parFactory ( fields , strict = 0 ) : if len ( fields ) < 3 or None in fields [ 0 : 3 ] : raise SyntaxError ( "At least 3 fields must be given" ) type = fields [ 1 ] if type in _string_types : return IrafParS ( fields , strict ) elif type == 'R' : return StrictParR ( fields , 1 ) elif type in _real_types : return Ir...
parameter factory function
4,875
def setCmdline ( self , value = 1 ) : if value : self . __dict__ [ 'flags' ] = self . flags | _cmdlineFlag else : self . __dict__ [ 'flags' ] = self . flags & ~ _cmdlineFlag
Set cmdline flag
4,876
def setChanged ( self , value = 1 ) : if value : self . __dict__ [ 'flags' ] = self . flags | _changedFlag else : self . __dict__ [ 'flags' ] = self . flags & ~ _changedFlag
Set changed flag
4,877
def isLearned ( self , mode = None ) : if "l" in self . mode : return 1 if "h" in self . mode : return 0 if "a" in self . mode : if mode is None : mode = 'ql' if "h" in mode and "l" not in mode : return 0 return 1
Return true if this parameter is learned
4,878
def getWithPrompt ( self ) : if self . prompt : pstring = self . prompt . split ( "\n" ) [ 0 ] . strip ( ) else : pstring = self . name if self . choice : schoice = list ( map ( self . toString , self . choice ) ) pstring = pstring + " (" + "|" . join ( schoice ) + ")" elif self . min not in [ None , INDEF ] or self . ...
Interactively prompt for parameter value
4,879
def checkOneValue ( self , v , strict = 0 ) : if v in [ None , INDEF ] or ( isinstance ( v , str ) and v [ : 1 ] == ")" ) : return v elif v == "" : return None elif self . choice is not None and v not in self . choiceDict : schoice = list ( map ( self . toString , self . choice ) ) schoice = "|" . join ( schoice ) rais...
Checks a single value to see if it is in range or choice list
4,880
def pretty ( self , verbose = 0 ) : plines = self . prompt . split ( '\n' ) for i in range ( len ( plines ) - 1 ) : plines [ i + 1 ] = 32 * ' ' + plines [ i + 1 ] plines = '\n' . join ( plines ) namelen = min ( len ( self . name ) , 12 ) pvalue = self . get ( prompt = 0 , lpar = 1 ) alwaysquoted = [ 's' , 'f' , '*gcur'...
Return pretty list description of parameter
4,881
def _setChoice ( self , s , strict = 0 ) : clist = _getChoice ( s , strict ) self . choice = list ( map ( self . _coerceValue , clist ) ) self . _setChoiceDict ( )
Set choice parameter from string s
4,882
def _setChoiceDict ( self ) : self . choiceDict = { } for c in self . choice : self . choiceDict [ c ] = c
Create dictionary for choice list
4,883
def _optionalPrompt ( self , mode ) : if ( self . mode == "h" ) or ( self . mode == "a" and mode == "h" ) : if not self . isLegal ( ) : self . getWithPrompt ( ) elif self . mode == "u" : if not self . isLegal ( ) : raise ValueError ( "Attempt to access undefined local variable `%s'" % self . name ) else : if self . isC...
Interactively prompt for parameter if necessary
4,884
def _getPFilename ( self , native , prompt ) : return self . get ( native = native , prompt = prompt )
Get p_filename field for this parameter
4,885
def _getField ( self , field , native = 0 , prompt = 1 ) : try : field = _getFieldDict [ field ] except KeyError as e : raise SyntaxError ( "Cannot get field " + field + " for parameter " + self . name + "\n" + str ( e ) ) if field == "p_value" : return self . get ( native = native , prompt = prompt ) elif field == "p_...
Get a parameter field value
4,886
def _setField ( self , value , field , check = 1 ) : try : field = _setFieldDict [ field ] except KeyError as e : raise SyntaxError ( "Cannot set field " + field + " for parameter " + self . name + "\n" + str ( e ) ) if field == "p_prompt" : self . prompt = irafutils . removeEscapes ( irafutils . stripQuotes ( value ) ...
Set a parameter field value
4,887
def _sumindex ( self , index = None ) : try : ndim = len ( index ) except TypeError : index = ( index , ) ndim = 1 if len ( self . shape ) != ndim : raise ValueError ( "Index to %d-dimensional array %s has too %s dimensions" % ( len ( self . shape ) , self . name , [ "many" , "few" ] [ len ( self . shape ) > ndim ] ) )...
Convert tuple index to 1 - D index into value
4,888
def _coerceValue ( self , value , strict = 0 ) : try : if isinstance ( value , str ) : value = value . split ( ) if len ( value ) != len ( self . value ) : raise IndexError v = len ( self . value ) * [ 0 ] for i in range ( len ( v ) ) : v [ i ] = self . _coerceOneValue ( value [ i ] , strict ) return v except ( IndexEr...
Coerce parameter to appropriate type
4,889
def _setChoiceDict ( self ) : self . choiceDict = minmatch . MinMatchDict ( ) for c in self . choice : self . choiceDict . add ( c , c )
Create min - match dictionary for choice list
4,890
def legal_date ( year , month , day ) : if month == 2 : daysinmonth = 29 if isleap ( year ) else 28 else : daysinmonth = 30 if month in HAVE_30_DAYS else 31 if not ( 0 < day <= daysinmonth ) : raise ValueError ( "Month {} doesn't have a day {}" . format ( month , day ) ) return True
Check if this is a legal date in the Gregorian calendar
4,891
def to_jd2 ( year , month , day ) : legal_date ( year , month , day ) if month <= 2 : year = year - 1 month = month + 12 a = floor ( year / 100 ) b = floor ( a / 4 ) c = 2 - a + b e = floor ( 365.25 * ( year + 4716 ) ) f = floor ( 30.6001 * ( month + 1 ) ) return c + day + e + f - 1524.5
Gregorian to Julian Day Count for years between 1801 - 2099
4,892
def to_jd ( year , month , day ) : "Retrieve the Julian date equivalent for this date" return day + ( month - 1 ) * 30 + ( year - 1 ) * 365 + floor ( year / 4 ) + EPOCH - 1
Retrieve the Julian date equivalent for this date
4,893
def from_jd ( jdc ) : "Create a new date from a Julian date." cdc = floor ( jdc ) + 0.5 - EPOCH year = floor ( ( cdc - floor ( ( cdc + 366 ) / 1461 ) ) / 365 ) + 1 yday = jdc - to_jd ( year , 1 , 1 ) month = floor ( yday / 30 ) + 1 day = yday - ( month - 1 ) * 30 + 1 return year , month , day
Create a new date from a Julian date .
4,894
def print_archive ( self , format = True ) : if len ( list ( self . orig_wcs . keys ( ) ) ) > 0 : block = 'Original WCS keywords for ' + self . rootname + '\n' block += ' backed up on ' + repr ( self . orig_wcs [ 'WCSCDATE' ] ) + '\n' if not format : for key in self . wcstrans . keys ( ) : block += key . upper ( ) +...
Prints out archived WCS keywords .
4,895
def set_orient ( self ) : self . orient = RADTODEG ( N . arctan2 ( self . cd12 , self . cd22 ) )
Return the computed orientation based on CD matrix .
4,896
def updateWCS ( self , pixel_scale = None , orient = None , refpos = None , refval = None , size = None ) : _updateCD = no if orient is not None and orient != self . orient : pa = DEGTORAD ( orient ) self . orient = orient self . _orient_lin = orient _updateCD = yes else : pa = DEGTORAD ( self . orient ) if pixel_scale...
Create a new CD Matrix from the absolute pixel scale and reference image orientation .
4,897
def xy2rd ( self , pos ) : if self . ctype1 . find ( 'TAN' ) < 0 or self . ctype2 . find ( 'TAN' ) < 0 : print ( 'XY2RD only supported for TAN projections.' ) raise TypeError if isinstance ( pos , N . ndarray ) : posx = pos [ : , 0 ] posy = pos [ : , 1 ] else : posx = pos [ 0 ] posy = pos [ 1 ] xi = self . cd11 * ( pos...
This method would apply the WCS keywords to a position to generate a new sky position .
4,898
def rotateCD ( self , orient ) : _delta = self . get_orient ( ) - orient if _delta == 0. : return _rot = fileutil . buildRotMatrix ( _delta ) _cd = N . array ( [ [ self . cd11 , self . cd12 ] , [ self . cd21 , self . cd22 ] ] , dtype = N . float64 ) _cdrot = N . dot ( _cd , _rot ) self . cd11 = _cdrot [ 0 ] [ 0 ] self ...
Rotates WCS CD matrix to new orientation given by orient
4,899
def write ( self , fitsname = None , wcs = None , archive = True , overwrite = False , quiet = True ) : self . update ( ) image = self . rootname _fitsname = fitsname if image . find ( '.fits' ) < 0 and _fitsname is not None : self . geisname = image image = self . rootname = _fitsname fimg = fileutil . openImage ( ima...
Write out the values of the WCS keywords to the specified image .