idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
4,900 | def restore ( self ) : if len ( list ( self . backup . keys ( ) ) ) == 0 : return for key in self . backup . keys ( ) : if key != 'WCSCDATE' : self . __dict__ [ self . wcstrans [ key ] ] = self . orig_wcs [ self . backup [ key ] ] self . update ( ) | Reset the active WCS keywords to values stored in the backup keywords . |
4,901 | def archive ( self , prepend = None , overwrite = no , quiet = yes ) : if len ( list ( self . backup . keys ( ) ) ) > 0 and overwrite == no : if not quiet : print ( 'WARNING: Backup WCS keywords already exist! No backup made.' ) print ( ' The values can only be overridden if overwrite=yes.' ) return if prepend ... | Create backup copies of the WCS keywords with the given prepended string . If backup keywords are already present only update them if overwrite is set to yes otherwise do warn the user and do nothing . Set the WCSDATE at this time as well . |
4,902 | def read_archive ( self , header , prepend = None ) : _prefix = None _archive = False if header is not None : for kw in header . items ( ) : if kw [ 0 ] [ 1 : ] in self . wcstrans . keys ( ) : _prefix = kw [ 0 ] [ 0 ] _archive = True break if not _archive : self . archive ( prepend = prepend ) return if _prefix is not ... | Extract a copy of WCS keywords from an open file header if they have already been created and remember the prefix used for those keywords . Otherwise setup the current WCS keywords as the archive values . |
4,903 | def restoreWCS ( self , prepend = None ) : image = self . rootname if prepend : _prepend = prepend elif self . prepend : _prepend = self . prepend else : _prepend = None fimg = fileutil . openImage ( image , mode = 'update' ) _root , _iextn = fileutil . parseFilename ( self . rootname ) _extn = fileutil . getExtn ( fim... | Resets the WCS values to the original values stored in the backup keywords recorded in self . backup . |
4,904 | def createReferenceWCS ( self , refname , overwrite = yes ) : hdu = self . createWcsHDU ( ) if os . path . exists ( refname ) : if overwrite == yes : os . remove ( refname ) hdu . writeto ( refname ) else : wcs_append = True oldhdu = fits . open ( refname , mode = 'append' ) for e in oldhdu : if 'extname' in e . header... | Write out the values of the WCS keywords to the NEW specified image fitsname . |
4,905 | def to_jd ( year , month , day , method = None ) : method = method or 'equinox' if day < 1 or day > 30 : raise ValueError ( "Invalid day for this calendar" ) if month > 13 : raise ValueError ( "Invalid month for this calendar" ) if month == 13 and day > 5 + leap ( year , method = method ) : raise ValueError ( "Invalid ... | Obtain Julian day from a given French Revolutionary calendar date . |
4,906 | def _to_jd_schematic ( year , month , day , method ) : y0 , y1 , y2 , y3 , y4 , y5 = 0 , 0 , 0 , 0 , 0 , 0 intercal_cycle_yrs , over_cycle_yrs , leap_suppression_yrs = None , None , None if ( ( method in ( 100 , 'romme' ) and year < 15 ) or ( method in ( 128 , 'madler' ) and year < 17 ) ) : method = 4 if method in ( 4 ... | Calculate JD using various leap - year calculation methods |
4,907 | def from_jd ( jd , method = None ) : method = method or 'equinox' if method == 'equinox' : return _from_jd_equinox ( jd ) else : return _from_jd_schematic ( jd , method ) | Calculate date in the French Revolutionary calendar from Julian day . The five or six sansculottides are considered a thirteenth month in the results of this function . |
4,908 | def _from_jd_schematic ( jd , method ) : if jd < EPOCH : raise ValueError ( "Can't convert days before the French Revolution" ) J = trunc ( jd ) + 0.5 - EPOCH y0 , y1 , y2 , y3 , y4 , y5 = 0 , 0 , 0 , 0 , 0 , 0 intercal_cycle_days = leap_suppression_days = over_cycle_days = None if ( J <= DAYS_IN_YEAR * 12 + 3 and meth... | Convert from JD using various leap - year calculation methods |
4,909 | def _from_jd_equinox ( jd ) : jd = trunc ( jd ) + 0.5 equinoxe = premier_da_la_annee ( jd ) an = gregorian . from_jd ( equinoxe ) [ 0 ] - YEAR_EPOCH mois = trunc ( ( jd - equinoxe ) / 30. ) + 1 jour = int ( ( jd - equinoxe ) % 30 ) + 1 return ( an , mois , jour ) | Calculate the FR day using the equinox as day 1 |
4,910 | def to_jd ( year , month , day ) : gyear = year + 78 leap = isleap ( gyear ) start = gregorian . to_jd ( gyear , 3 , 22 - leap ) if leap : Caitra = 31 else : Caitra = 30 if month == 1 : jd = start + ( day - 1 ) else : jd = start + Caitra m = month - 2 m = min ( m , 5 ) jd += m * 31 if month >= 8 : m = month - 7 jd += m... | Obtain Julian day for Indian Civil date |
4,911 | def from_jd ( jd ) : start = 80 jd = trunc ( jd ) + 0.5 greg = gregorian . from_jd ( jd ) leap = isleap ( greg [ 0 ] ) year = greg [ 0 ] - SAKA_EPOCH greg0 = gregorian . to_jd ( greg [ 0 ] , 1 , 1 ) yday = jd - greg0 if leap : Caitra = 31 else : Caitra = 30 if yday < start : year -= 1 yday += Caitra + ( 31 * 5 ) + ( 30... | Calculate Indian Civil date from Julian day Offset in years from Saka era to Gregorian epoch |
4,912 | def format_stack ( skip = 0 , length = 6 , _sep = os . path . sep ) : return ' < ' . join ( "%s:%s:%s" % ( '/' . join ( f . f_code . co_filename . split ( _sep ) [ - 2 : ] ) , f . f_lineno , f . f_code . co_name ) for f in islice ( frame_iterator ( sys . _getframe ( 1 + skip ) ) , length ) ) | Returns a one - line string with the current callstack . |
4,913 | def get ( self , deviceId ) : measurementsByName = self . measurements . get ( deviceId ) if measurementsByName is None : return [ ] else : return list ( measurementsByName . values ( ) ) | lists all known active measurements . |
4,914 | def get ( self , deviceId , measurementId ) : record = self . measurements . get ( deviceId ) if record is not None : return record . get ( measurementId ) return None | details the specific measurement . |
4,915 | def clicked ( self ) : try : from . import teal except : teal = None try : tealGui = self . _mainGuiObj tealGui . showStatus ( 'Clicked "' + self . getButtonLabel ( ) + '"' , keep = 1 ) pscope = self . paramInfo . scope pname = self . paramInfo . name tpo = tealGui . _taskParsObj tup = tpo . getExecuteStrings ( pscope ... | Called when this button is clicked . Execute code from . cfgspc |
4,916 | def tobytes ( s , encoding = 'ascii' ) : if PY3K : if isinstance ( s , bytes ) : return s else : return s . encode ( encoding ) else : if isinstance ( s , unicode ) : return s . encode ( encoding ) else : return s | Convert string s to the bytes type in all Pythons even back before Python 2 . 6 . What str means varies by PY3K or not . In Pythons before 3 . 0 this is technically the same as the str type in terms of the character data in memory . |
4,917 | def tostr ( s , encoding = 'ascii' ) : if PY3K : if isinstance ( s , str ) : return s else : return s . decode ( encoding ) else : if isinstance ( s , unicode ) : return s . encode ( encoding ) else : return s | Convert string - like - thing s to the str type in all Pythons even back before Python 2 . 6 . What str means varies by PY3K or not . In Pythons before 3 . 0 str and bytes are the same type . In Python 3 + this may require a decoding step . |
4,918 | def retry ( func = None , retries = 5 , backoff = None , exceptions = ( IOError , OSError , EOFError ) , cleanup = None , sleep = time . sleep ) : @ Aspect ( bind = True ) def retry_aspect ( cutpoint , * args , ** kwargs ) : for count in range ( retries + 1 ) : try : if count and cleanup : cleanup ( * args , ** kwargs ... | Decorator that retries the call retries times if func raises exceptions . Can use a backoff function to sleep till next retry . |
4,919 | def eparOptionFactory ( master , statusBar , param , defaultParam , doScroll , fieldWidths , plugIn = None , editedCallbackObj = None , helpCallbackObj = None , mainGuiObj = None , defaultsVerb = "Default" , bg = None , indent = False , flagging = False , flaggedColor = None ) : if plugIn is not None : eparOption = plu... | Return EparOption item of appropriate type for the parameter param |
4,920 | def popupChoices ( self , event = None ) : if NORMAL not in ( self . browserEnabled , self . clearEnabled , self . unlearnEnabled , self . helpEnabled ) : return self . menu = Menu ( self . entry , tearoff = 0 ) if self . browserEnabled != DISABLED : if capable . OF_TKFD_IN_EPAR : self . menu . add_command ( label = "F... | Popup right - click menu of special parameter operations |
4,921 | def fileBrowser ( self ) : if capable . OF_TKFD_IN_EPAR : fname = askopenfilename ( parent = self . entry , title = "Select File" ) else : from . import filedlg self . fd = filedlg . PersistLoadFileDialog ( self . entry , "Select File" , "*" ) if self . fd . Show ( ) != 1 : self . fd . DialogCleanup ( ) return fname = ... | Invoke a tkinter file dialog |
4,922 | def dirBrowser ( self ) : if capable . OF_TKFD_IN_EPAR : fname = askdirectory ( parent = self . entry , title = "Select Directory" ) else : raise NotImplementedError ( 'Fix popupChoices() logic.' ) if not fname : return self . choice . set ( fname ) self . lastSelection = None | Invoke a tkinter directory dialog |
4,923 | def forceValue ( self , newVal , noteEdited = False ) : if newVal is None : newVal = "" self . choice . set ( newVal ) if noteEdited : self . widgetEdited ( val = newVal , skipDups = False ) | Force - set a parameter entry to the given value |
4,924 | def unlearnValue ( self ) : defaultValue = self . defaultParamInfo . get ( field = "p_filename" , native = 0 , prompt = 0 ) self . choice . set ( defaultValue ) | Unlearn a parameter value by setting it back to its default |
4,925 | def keypress ( self , event ) : try : self . choice . set ( self . shortcuts [ event . keysym ] ) except KeyError : pass | Allow keys typed in widget to select items |
4,926 | def postcmd ( self ) : value = self . choice . get ( ) try : index = self . paramInfo . choice . index ( value ) self . entry . menu . activate ( index ) except ValueError : pass | Make sure proper entry is activated when menu is posted |
4,927 | def convertToNative ( self , aVal ) : if aVal is None : return None if isinstance ( aVal , bool ) : return aVal return str ( aVal ) . lower ( ) in ( '1' , 'on' , 'yes' , 'true' ) | Convert to native bool ; interpret certain strings . |
4,928 | def toggle ( self , event = None ) : if self . choice . get ( ) == "yes" : self . rbno . select ( ) else : self . rbyes . select ( ) self . widgetEdited ( ) | Toggle value between Yes and No |
4,929 | def entryCheck ( self , event = None , repair = True ) : valupr = self . choice . get ( ) . upper ( ) if valupr . strip ( ) == 'INDEF' : self . choice . set ( valupr ) return EparOption . entryCheck ( self , event , repair = repair ) | Ensure any INDEF entry is uppercase before base class behavior |
4,930 | def _setSampleSizeBytes ( self ) : self . sampleSizeBytes = self . getPacketSize ( ) if self . sampleSizeBytes > 0 : self . maxBytesPerFifoRead = ( 32 // self . sampleSizeBytes ) | updates the current record of the packet size per sample and the relationship between this and the fifo reads . |
4,931 | def easter ( year ) : c = trunc ( year / 100 ) n = year - 19 * trunc ( year / 19 ) k = trunc ( ( c - 17 ) / 25 ) i = c - trunc ( c / 4 ) - trunc ( ( c - k ) / 3 ) + ( 19 * n ) + 15 i = i - 30 * trunc ( i / 30 ) i = i - trunc ( i / 28 ) * ( 1 - trunc ( i / 28 ) * trunc ( 29 / ( i + 1 ) ) * trunc ( ( 21 - n ) / 11 ) ) j ... | Calculate western easter |
4,932 | def convert ( input , width = 132 , output = None , keep = False ) : trl = open ( input ) lines = np . array ( [ i for text in trl . readlines ( ) for i in textwrap . wrap ( text , width = width ) ] ) trl . close ( ) if output is None : rootname , suffix = os . path . splitext ( input ) s = suffix [ 1 : ] . replace ( '... | Input ASCII trailer file input will be read . |
4,933 | def get_extra_values ( conf , _prepend = ( ) ) : out = [ ] out . extend ( [ ( _prepend , name ) for name in conf . extra_values ] ) for name in conf . sections : if name not in conf . extra_values : out . extend ( get_extra_values ( conf [ name ] , _prepend + ( name , ) ) ) return out | Find all the values and sections not in the configspec from a validated ConfigObj . |
4,934 | def _fetch ( self , key ) : save_interp = self . section . main . interpolation self . section . main . interpolation = False current_section = self . section while True : val = current_section . get ( key ) if val is not None and not isinstance ( val , Section ) : break val = current_section . get ( 'DEFAULT' , { } ) ... | Helper function to fetch values from owning section . |
4,935 | def dict ( self ) : newdict = { } for entry in self : this_entry = self [ entry ] if isinstance ( this_entry , Section ) : this_entry = this_entry . dict ( ) elif isinstance ( this_entry , list ) : this_entry = list ( this_entry ) elif isinstance ( this_entry , tuple ) : this_entry = tuple ( this_entry ) newdict [ entr... | Return a deepcopy of self as a dictionary . |
4,936 | def merge ( self , indict ) : for key , val in list ( indict . items ( ) ) : if ( key in self and isinstance ( self [ key ] , dict ) and isinstance ( val , dict ) ) : self [ key ] . merge ( val ) else : self [ key ] = val | A recursive update - useful for merging config files . |
4,937 | def rename ( self , oldkey , newkey ) : if oldkey in self . scalars : the_list = self . scalars elif oldkey in self . sections : the_list = self . sections else : raise KeyError ( 'Key "%s" not found.' % oldkey ) pos = the_list . index ( oldkey ) val = self [ oldkey ] dict . __delitem__ ( self , oldkey ) dict . __setit... | Change a keyname to another without changing position in sequence . |
4,938 | def walk ( self , function , raise_errors = True , call_on_sections = False , ** keywargs ) : out = { } for i in range ( len ( self . scalars ) ) : entry = self . scalars [ i ] try : val = function ( self , entry , ** keywargs ) entry = self . scalars [ i ] out [ entry ] = val except Exception : if raise_errors : raise... | Walk every member and call a function on the keyword and value . |
4,939 | def as_list ( self , key ) : result = self [ key ] if isinstance ( result , ( tuple , list ) ) : return list ( result ) return [ result ] | A convenience method which fetches the specified value guaranteeing that it is a list . |
4,940 | def restore_defaults ( self ) : for key in self . default_values : self . restore_default ( key ) for section in self . sections : self [ section ] . restore_defaults ( ) | Recursively restore default values to all members that have them . |
4,941 | def _handle_bom ( self , infile ) : if ( ( self . encoding is not None ) and ( self . encoding . lower ( ) not in BOM_LIST ) ) : return self . _decode ( infile , self . encoding ) if isinstance ( infile , ( list , tuple ) ) : line = infile [ 0 ] else : line = infile if self . encoding is not None : enc = BOM_LIST [ sel... | Handle any BOM and decode if necessary . |
4,942 | def _decode ( self , infile , encoding ) : if isinstance ( infile , string_types ) : return infile . decode ( encoding ) . splitlines ( True ) for i , line in enumerate ( infile ) : if PY3K : if not isinstance ( line , str ) : infile [ i ] = line . decode ( encoding ) else : if not isinstance ( line , unicode ) : infil... | Decode infile to unicode . Using the specified encoding . |
4,943 | def _decode_element ( self , line ) : if not self . encoding : return line if isinstance ( line , str ) and self . default_encoding : return line . decode ( self . default_encoding ) return line | Decode element to unicode if necessary . |
4,944 | def _match_depth ( self , sect , depth ) : while depth < sect . depth : if sect is sect . parent : raise SyntaxError ( ) sect = sect . parent if sect . depth == depth : return sect raise SyntaxError ( ) | Given a section and a depth level walk back through the sections parents to see if the depth level matches a previous section . |
4,945 | def _handle_error ( self , text , ErrorClass , infile , cur_index ) : line = infile [ cur_index ] cur_index += 1 message = text % cur_index error = ErrorClass ( message , cur_index , line ) if self . raise_errors : raise error self . _errors . append ( error ) | Handle an error according to the error settings . |
4,946 | def _unquote ( self , value ) : if not value : raise SyntaxError if ( value [ 0 ] == value [ - 1 ] ) and ( value [ 0 ] in ( '"' , "'" ) ) : value = value [ 1 : - 1 ] return value | Return an unquoted version of a value |
4,947 | def _quote ( self , value , multiline = True ) : if multiline and self . write_empty_values and value == '' : return '' if multiline and isinstance ( value , ( list , tuple ) ) : if not value : return ',' elif len ( value ) == 1 : return self . _quote ( value [ 0 ] , multiline = False ) + ',' return ', ' . join ( [ sel... | Return a safely quoted version of a value . |
4,948 | def _multiline ( self , value , infile , cur_index , maxline ) : quot = value [ : 3 ] newvalue = value [ 3 : ] single_line = self . _triple_quote [ quot ] [ 0 ] multi_line = self . _triple_quote [ quot ] [ 1 ] mat = single_line . match ( value ) if mat is not None : retval = list ( mat . groups ( ) ) retval . append ( ... | Extract the value where we are in a multiline situation . |
4,949 | def _handle_configspec ( self , configspec ) : if not isinstance ( configspec , ConfigObj ) : try : configspec = ConfigObj ( configspec , raise_errors = True , file_error = True , _inspec = True ) except ConfigObjError as e : raise ConfigspecError ( 'Parsing configspec failed: %s' % e ) except IOError as e : raise IOEr... | Parse the configspec . |
4,950 | def _write_line ( self , indent_string , entry , this_entry , comment ) : if not self . unrepr : val = self . _decode_element ( self . _quote ( this_entry ) ) else : val = repr ( this_entry ) return '%s%s%s%s%s' % ( indent_string , self . _decode_element ( self . _quote ( entry , multiline = False ) ) , self . _a_to_u ... | Write an individual line for the write method |
4,951 | def _write_marker ( self , indent_string , depth , entry , comment ) : return '%s%s%s%s%s' % ( indent_string , self . _a_to_u ( '[' * depth ) , self . _quote ( self . _decode_element ( entry ) , multiline = False ) , self . _a_to_u ( ']' * depth ) , self . _decode_element ( comment ) ) | Write a section marker line |
4,952 | def _handle_comment ( self , comment ) : if not comment : return '' start = self . indent_type if not comment . startswith ( '#' ) : start += self . _a_to_u ( ' # ' ) return ( start + comment ) | Deal with a comment . |
4,953 | def reset ( self ) : self . clear ( ) self . _initialise ( ) self . configspec = None self . _original_configspec = None | Clear ConfigObj instance and restore to freshly created state . |
4,954 | def reload ( self ) : if not isinstance ( self . filename , string_types ) : raise ReloadError ( ) filename = self . filename current_options = { } for entry in OPTION_DEFAULTS : if entry == 'configspec' : continue current_options [ entry ] = getattr ( self , entry ) configspec = self . _original_configspec current_opt... | Reload a ConfigObj from file . |
4,955 | def check ( self , check , member , missing = False ) : if missing : raise self . baseErrorClass ( ) return member | A dummy check method always returns the value unchanged . |
4,956 | def _verify ( waiveredHdul ) : if len ( waiveredHdul ) == 2 : if waiveredHdul [ 0 ] . header [ 'NAXIS' ] > 0 : if isinstance ( waiveredHdul [ 1 ] , fits . TableHDU ) : if waiveredHdul [ 0 ] . data . shape [ 0 ] == waiveredHdul [ 1 ] . data . shape [ 0 ] or waiveredHdul [ 1 ] . data . shape [ 0 ] == 1 : return raise Val... | Verify that the input HDUList is for a waivered FITS file . |
4,957 | def convertwaiveredfits ( waiveredObject , outputFileName = None , forceFileOutput = False , convertTo = 'multiExtension' , verbose = False ) : if convertTo == 'multiExtension' : func = toMultiExtensionFits else : raise ValueError ( 'Conversion type ' + convertTo + ' unknown' ) return func ( * ( waiveredObject , output... | Convert the input waivered FITS object to various formats . The default conversion format is multi - extension FITS . Generate an output file in the desired format if requested . |
4,958 | def to_jd ( year , month , day ) : if year >= 0 : y = 474 else : y = 473 epbase = year - y epyear = 474 + ( epbase % 2820 ) if month <= 7 : m = ( month - 1 ) * 31 else : m = ( month - 1 ) * 30 + 6 return day + m + trunc ( ( ( epyear * 682 ) - 110 ) / 2816 ) + ( epyear - 1 ) * 365 + trunc ( epbase / 2820 ) * 1029983 + (... | Determine Julian day from Persian date |
4,959 | def from_jd ( jd ) : jd = trunc ( jd ) + 0.5 depoch = jd - to_jd ( 475 , 1 , 1 ) cycle = trunc ( depoch / 1029983 ) cyear = ( depoch % 1029983 ) if cyear == 1029982 : ycycle = 2820 else : aux1 = trunc ( cyear / 366 ) aux2 = cyear % 366 ycycle = trunc ( ( ( 2134 * aux1 ) + ( 2816 * aux2 ) + 2815 ) / 1028522 ) + aux1 + 1... | Calculate Persian date from Julian day |
4,960 | def teardown_global_logging ( ) : global global_logging_started if not global_logging_started : return stdout_logger = logging . getLogger ( __name__ + '.stdout' ) stderr_logger = logging . getLogger ( __name__ + '.stderr' ) if sys . stdout is stdout_logger : sys . stdout = sys . stdout . stream if sys . stderr is stde... | Disable global logging of stdio warnings and exceptions . |
4,961 | def create_logger ( name , format = '%(levelname)s: %(message)s' , datefmt = None , stream = None , level = logging . INFO , filename = None , filemode = 'w' , filelevel = None , propagate = True ) : logger = logging . getLogger ( name ) logger . setLevel ( level ) fmt = logging . Formatter ( format , datefmt ) logger ... | Do basic configuration for the logging system . Similar to logging . basicConfig but the logger name is configurable and both a file output and a stream output can be created . Returns a logger object . |
4,962 | def _post_login_page ( self , login_url ) : data = { "login" : self . username , "_58_password" : self . password } try : raw_res = yield from self . _session . post ( login_url , data = data , timeout = self . _timeout , allow_redirects = False ) except OSError : raise PyHydroQuebecError ( "Can not submit login form" ... | Login to HydroQuebec website . |
4,963 | def _get_p_p_id_and_contract ( self ) : contracts = { } try : raw_res = yield from self . _session . get ( PROFILE_URL , timeout = self . _timeout ) except OSError : raise PyHydroQuebecError ( "Can not get profile page" ) content = yield from raw_res . text ( ) soup = BeautifulSoup ( content , 'html.parser' ) for node ... | Get id of consumption profile . |
4,964 | def _get_lonely_contract ( self ) : contracts = { } try : raw_res = yield from self . _session . get ( MAIN_URL , timeout = self . _timeout ) except OSError : raise PyHydroQuebecError ( "Can not get main page" ) content = yield from raw_res . text ( ) soup = BeautifulSoup ( content , 'html.parser' ) info_node = soup . ... | Get contract number when we have only one contract . |
4,965 | def _get_balances ( self ) : balances = [ ] try : raw_res = yield from self . _session . get ( MAIN_URL , timeout = self . _timeout ) except OSError : raise PyHydroQuebecError ( "Can not get main page" ) content = yield from raw_res . text ( ) soup = BeautifulSoup ( content , 'html.parser' ) solde_nodes = soup . find_a... | Get all balances . |
4,966 | def _load_contract_page ( self , contract_url ) : try : yield from self . _session . get ( contract_url , timeout = self . _timeout ) except OSError : raise PyHydroQuebecError ( "Can not get profile page for a " "specific contract" ) | Load the profile page of a specific contract when we have multiple contracts . |
4,967 | def _get_annual_data ( self , p_p_id ) : params = { "p_p_id" : p_p_id , "p_p_lifecycle" : 2 , "p_p_state" : "normal" , "p_p_mode" : "view" , "p_p_resource_id" : "resourceObtenirDonneesConsommationAnnuelles" } try : raw_res = yield from self . _session . get ( PROFILE_URL , params = params , timeout = self . _timeout ) ... | Get annual data . |
4,968 | def _get_monthly_data ( self , p_p_id ) : params = { "p_p_id" : p_p_id , "p_p_lifecycle" : 2 , "p_p_resource_id" : ( "resourceObtenirDonnees" "PeriodesConsommation" ) } try : raw_res = yield from self . _session . get ( PROFILE_URL , params = params , timeout = self . _timeout ) except OSError : raise PyHydroQuebecErro... | Get monthly data . |
4,969 | def _get_hourly_data ( self , day_date , p_p_id ) : params = { "p_p_id" : p_p_id , "p_p_lifecycle" : 2 , "p_p_state" : "normal" , "p_p_mode" : "view" , "p_p_resource_id" : "resourceObtenirDonneesConsommationHoraires" , "p_p_cacheability" : "cacheLevelPage" , "p_p_col_id" : "column-2" , "p_p_col_count" : 1 , "date" : da... | Get Hourly Data . |
4,970 | def fetch_data_detailled_energy_use ( self , start_date = None , end_date = None ) : if start_date is None : start_date = datetime . datetime . now ( HQ_TIMEZONE ) - datetime . timedelta ( days = 1 ) if end_date is None : end_date = datetime . datetime . now ( HQ_TIMEZONE ) yield from self . _get_httpsession ( ) login_... | Get detailled energy use from a specific contract . |
4,971 | def fetch_data ( self ) : yield from self . _get_httpsession ( ) login_url = yield from self . _get_login_page ( ) yield from self . _post_login_page ( login_url ) p_p_id , contracts = yield from self . _get_p_p_id_and_contract ( ) if contracts == { } : contracts = yield from self . _get_lonely_contract ( ) balances = ... | Get the latest data from HydroQuebec . |
4,972 | def get_data ( self , contract = None ) : if contract is None : return self . _data if contract in self . _data . keys ( ) : return { contract : self . _data [ contract ] } raise PyHydroQuebecError ( "Contract {} not found" . format ( contract ) ) | Return collected data . |
4,973 | def _validate_argument ( self , arg ) : if arg is None : return arg if isinstance ( arg , type ) : return InstanceOf ( arg ) if not isinstance ( arg , BaseMatcher ) : raise TypeError ( "argument of %s can be a type or a matcher (got %r)" % ( self . __class__ . __name__ , type ( arg ) ) ) return arg | Validate a type or matcher argument to the constructor . |
4,974 | def _initialize ( self , * args , ** kwargs ) : self . items = None self . keys = None self . values = None if args : if len ( args ) != 2 : raise TypeError ( "expected exactly two positional arguments, " "got %s" % len ( args ) ) if kwargs : raise TypeError ( "expected positional or keyword arguments, not both" ) self... | Initiaize the mapping matcher with constructor arguments . |
4,975 | def docs ( ctx , output = 'html' , rebuild = False , show = True , verbose = True ) : sphinx_build = ctx . run ( 'sphinx-build -b {output} {all} {verbose} docs docs/_build' . format ( output = output , all = '-a -E' if rebuild else '' , verbose = '-v' if verbose else '' ) ) if not sphinx_build . ok : fatal ( "Failed to... | Build the docs and show them in default web browser . |
4,976 | def upload ( ctx , yes = False ) : import callee version = callee . __version__ if version . endswith ( '-dev' ) : fatal ( "Can't upload a development version (%s) to PyPI!" , version ) if not yes : answer = input ( "Do you really want to upload to PyPI [y/N]? " ) yes = answer . strip ( ) . lower ( ) == 'y' if not yes ... | Upload the package to PyPI . |
4,977 | def fatal ( * args , ** kwargs ) : exitcode = None if 'exitcode' in kwargs : exitcode = kwargs . pop ( 'exitcode' ) if 'cause' in kwargs : cause = kwargs . pop ( 'cause' ) if not isinstance ( cause , Result ) : raise TypeError ( "invalid cause of fatal error: expected %r, got %r" % ( Result , type ( cause ) ) ) exitcod... | Log an error message and exit . |
4,978 | def _add_request_parameters ( func ) : async def decorated_func ( * args , handle_ratelimit = None , max_tries = None , request_timeout = None , ** kwargs ) : return await func ( * args , handle_ratelimit = handle_ratelimit , max_tries = max_tries , request_timeout = request_timeout , ** kwargs ) return decorated_func | Adds the ratelimit and request timeout parameters to a function . |
4,979 | async def _base_request ( self , battle_tag : str , endpoint_name : str , session : aiohttp . ClientSession , * , platform = None , handle_ratelimit = None , max_tries = None , request_timeout = None ) : if platform is None : platform = self . default_platform if handle_ratelimit is None : handle_ratelimit = self . def... | Does a request to some endpoint . This is also where ratelimit logic is handled . |
4,980 | def is_method ( arg , min_arity = None , max_arity = None ) : if not callable ( arg ) : return False if not any ( is_ ( arg ) for is_ in ( inspect . ismethod , inspect . ismethoddescriptor , inspect . isbuiltin ) ) : return False try : argnames , varargs , kwargs , defaults = getargspec ( arg ) except TypeError : retur... | Check if argument is a method . |
4,981 | def _is_readable ( self , obj ) : try : read = getattr ( obj , 'read' ) except AttributeError : return False else : return is_method ( read , max_arity = 1 ) | Check if the argument is a readable file - like object . |
4,982 | def _is_writable ( self , obj ) : try : write = getattr ( obj , 'write' ) except AttributeError : return False else : return is_method ( write , min_arity = 1 , max_arity = 1 ) | Check if the argument is a writable file - like object . |
4,983 | def run ( time : datetime , altkm : float , glat : Union [ float , np . ndarray ] , glon : Union [ float , np . ndarray ] , * , f107a : float = None , f107 : float = None , Ap : int = None ) -> xarray . Dataset : glat = np . atleast_2d ( glat ) glon = np . atleast_2d ( glon ) if glat . size == 1 and glon . size == 1 an... | loops the rungtd1d function below . Figure it s easier to troubleshoot in Python than Fortran . |
4,984 | def loopalt_gtd ( time : datetime , glat : Union [ float , np . ndarray ] , glon : Union [ float , np . ndarray ] , altkm : Union [ float , List [ float ] , np . ndarray ] , * , f107a : float = None , f107 : float = None , Ap : int = None ) -> xarray . Dataset : glat = np . atleast_2d ( glat ) glon = np . atleast_2d ( ... | loop over location and time |
4,985 | def _validate_desc ( self , desc ) : if desc is None : return desc if not isinstance ( desc , STRING_TYPES ) : raise TypeError ( "predicate description for Matching must be a string, " "got %r" % ( type ( desc ) , ) ) if not IS_PY3 and isinstance ( desc , unicode ) : try : desc = desc . encode ( 'ascii' , errors = 'str... | Validate the predicate description . |
4,986 | def clean_email ( self ) : contacts = self . api . lists . contacts ( id = self . list_id ) [ 'result' ] for contact in contacts : if contact [ 'email' ] == self . cleaned_data [ 'email' ] : raise forms . ValidationError ( _ ( u'This email is already subscribed' ) ) return self . cleaned_data [ 'email' ] | Raise ValidationError if the contact exists . |
4,987 | def add_contact ( self ) : self . api . lists . addcontact ( contact = self . cleaned_data [ 'email' ] , id = self . list_id , method = 'POST' ) | Create a contact with using the email on the list . |
4,988 | def list_id ( self ) : list_id = getattr ( self , '_list_id' , None ) if list_id is None : for l in self . api . lists . all ( ) [ 'lists' ] : if l [ 'name' ] == self . list_name : self . _list_id = l [ 'id' ] if not getattr ( self , '_list_id' , None ) : self . _list_id = self . api . lists . create ( label = self . l... | Get or create the list id . |
4,989 | def read_tags ( filename ) : with open ( filename ) as f : ast_tree = ast . parse ( f . read ( ) , filename ) res = { } for node in ast . walk ( ast_tree ) : if type ( node ) is not ast . Assign : continue target = node . targets [ 0 ] if type ( target ) is not ast . Name : continue if not ( target . id . startswith ( ... | Reads values of magic tags defined in the given Python file . |
4,990 | def word_tokenize ( text , stopwords = _stopwords , ngrams = None , min_length = 0 , ignore_numeric = True ) : if ngrams is None : ngrams = 1 text = re . sub ( re . compile ( '\'s' ) , '' , text ) text = re . sub ( _re_punctuation , '' , text ) matched_tokens = re . findall ( _re_token , text . lower ( ) ) for tokens i... | Parses the given text and yields tokens which represent words within the given text . Tokens are assumed to be divided by any form of whitespace character . |
4,991 | def cmake_setup ( ) : cmake_exe = shutil . which ( 'cmake' ) if not cmake_exe : raise FileNotFoundError ( 'CMake not available' ) wopts = [ '-G' , 'MinGW Makefiles' , '-DCMAKE_SH="CMAKE_SH-NOTFOUND' ] if os . name == 'nt' else [ ] subprocess . check_call ( [ cmake_exe ] + wopts + [ str ( SRCDIR ) ] , cwd = BINDIR ) ret... | attempt to build using CMake > = 3 |
4,992 | def meson_setup ( ) : meson_exe = shutil . which ( 'meson' ) ninja_exe = shutil . which ( 'ninja' ) if not meson_exe or not ninja_exe : raise FileNotFoundError ( 'Meson or Ninja not available' ) if not ( BINDIR / 'build.ninja' ) . is_file ( ) : subprocess . check_call ( [ meson_exe , str ( SRCDIR ) ] , cwd = BINDIR ) r... | attempt to build with Meson + Ninja |
4,993 | def add_term_occurrence ( self , term , document ) : if document not in self . _documents : self . _documents [ document ] = 0 if term not in self . _terms : if self . _freeze : return else : self . _terms [ term ] = collections . Counter ( ) if document not in self . _terms [ term ] : self . _terms [ term ] [ document... | Adds an occurrence of the term in the specified document . |
4,994 | def get_total_term_frequency ( self , term ) : if term not in self . _terms : raise IndexError ( TERM_DOES_NOT_EXIST ) return sum ( self . _terms [ term ] . values ( ) ) | Gets the frequency of the specified term in the entire corpus added to the HashedIndex . |
4,995 | def get_term_frequency ( self , term , document , normalized = False ) : if document not in self . _documents : raise IndexError ( DOCUMENT_DOES_NOT_EXIST ) if term not in self . _terms : raise IndexError ( TERM_DOES_NOT_EXIST ) result = self . _terms [ term ] . get ( document , 0 ) if normalized : result /= self . get... | Returns the frequency of the term specified in the document . |
4,996 | def get_document_frequency ( self , term ) : if term not in self . _terms : raise IndexError ( TERM_DOES_NOT_EXIST ) else : return len ( self . _terms [ term ] ) | Returns the number of documents the specified term appears in . |
4,997 | def get_document_length ( self , document ) : if document in self . _documents : return self . _documents [ document ] else : raise IndexError ( DOCUMENT_DOES_NOT_EXIST ) | Returns the number of terms found within the specified document . |
4,998 | def get_documents ( self , term ) : if term not in self . _terms : raise IndexError ( TERM_DOES_NOT_EXIST ) else : return self . _terms [ term ] | Returns all documents related to the specified term in the form of a Counter object . |
4,999 | def get_tfidf ( self , term , document , normalized = False ) : tf = self . get_term_frequency ( term , document ) if tf != 0.0 : df = 1 + self . get_document_frequency ( term ) n = 2 + len ( self . _documents ) if normalized : tf /= self . get_document_length ( document ) return tf * math . log10 ( n / df ) else : ret... | Returns the Term - Frequency Inverse - Document - Frequency value for the given term in the specified document . If normalized is True term frequency will be divided by the document length . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.