idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
5,400 | def tabulate ( lol , headers , eol = '\n' ) : yield '| %s |' % ' | ' . join ( headers ) + eol yield '| %s:|' % ':| ' . join ( [ '-' * len ( w ) for w in headers ] ) + eol for row in lol : yield '| %s |' % ' | ' . join ( str ( c ) for c in row ) + eol | Use the pypi tabulate package instead! | 100 | 10 |
5,401 | def listify ( values , N = 1 , delim = None ) : ans = [ ] if values is None else values # convert non-string non-list iterables into a list if hasattr ( ans , '__iter__' ) and not isinstance ( ans , basestring ) : ans = list ( ans ) else : # split the string (if possible) if isinstance ( delim , basestring ) and isinstance ( ans , basestring ) : try : ans = ans . split ( delim ) except ( IndexError , ValueError , AttributeError , TypeError ) : ans = [ ans ] else : ans = [ ans ] # pad the end of the list if a length has been specified if len ( ans ) : if len ( ans ) < N and N > 1 : ans += [ ans [ - 1 ] ] * ( N - len ( ans ) ) else : if N > 1 : ans = [ [ ] ] * N return ans | Return an N - length list with elements values extrapolating as necessary . | 203 | 15 |
5,402 | def unlistify ( n , depth = 1 , typ = list , get = None ) : i = 0 if depth is None : depth = 1 index_desired = get or 0 while i < depth and isinstance ( n , typ ) : if len ( n ) : if len ( n ) > index_desired : n = n [ index_desired ] i += 1 else : return n return n | Return the desired element in a list ignoring the rest . | 87 | 11 |
5,403 | def strip_keys ( d , nones = False , depth = 0 ) : ans = type ( d ) ( ( str ( k ) . strip ( ) , v ) for ( k , v ) in viewitems ( OrderedDict ( d ) ) if ( not nones or ( str ( k ) . strip ( ) and str ( k ) . strip ( ) != 'None' ) ) ) if int ( depth ) < 1 : return ans if int ( depth ) > strip_keys . MAX_DEPTH : warnings . warn ( RuntimeWarning ( "Maximum recursion depth allowance (%r) exceeded." % strip_keys . MAX_DEPTH ) ) for k , v in viewitems ( ans ) : if isinstance ( v , Mapping ) : ans [ k ] = strip_keys ( v , nones = nones , depth = int ( depth ) - 1 ) return ans | r Strip whitespace from all dictionary keys to the depth indicated | 188 | 12 |
5,404 | def get_table_from_csv ( filename = 'ssg_report_aarons_returns.csv' , delimiter = ',' , dos = False ) : table = [ ] with open ( filename , 'rb' ) as f : reader = csv . reader ( f , dialect = 'excel' , delimiter = delimiter ) for row in reader : table += [ row ] if not dos : return table return dos_from_table ( table ) | Dictionary of sequences from CSV file | 101 | 7 |
5,405 | def shorten ( s , max_len = 16 ) : short = s words = [ abbreviate ( word ) for word in get_words ( s ) ] for i in range ( len ( words ) , 0 , - 1 ) : short = ' ' . join ( words [ : i ] ) if len ( short ) <= max_len : break return short [ : max_len ] | Attempt to shorten a phrase by deleting words at the end of the phrase | 81 | 14 |
5,406 | def truncate ( s , max_len = 20 , ellipsis = '...' ) : if s is None : return None elif isinstance ( s , basestring ) : return s [ : min ( len ( s ) , max_len ) ] + ellipsis if len ( s ) > max_len else '' elif isinstance ( s , Mapping ) : truncated_str = str ( dict ( islice ( viewitems ( s ) , max_len ) ) ) else : truncated_str = str ( list ( islice ( s , max_len ) ) ) return truncated_str [ : - 1 ] + '...' if len ( s ) > max_len else truncated_str | r Return string at most max_len characters or sequence elments appended with the ellipsis characters | 158 | 21 |
5,407 | def slash_product ( string_or_seq , slash = '/' , space = ' ' ) : # Terminating case is a sequence of strings without any slashes if not isinstance ( string_or_seq , basestring ) : # If it's not a string and has no slashes, we're done if not any ( slash in s for s in string_or_seq ) : return list ( string_or_seq ) ans = [ ] for s in string_or_seq : # slash_product of a string will always return a flat list ans += slash_product ( s ) return slash_product ( ans ) # Another terminating case is a single string without any slashes if slash not in string_or_seq : return [ string_or_seq ] # The third case is a string with some slashes in it i = string_or_seq . index ( slash ) head , tail = string_or_seq [ : i ] . split ( space ) , string_or_seq [ i + 1 : ] . split ( space ) alternatives = head [ - 1 ] , tail [ 0 ] head , tail = space . join ( head [ : - 1 ] ) , space . join ( tail [ 1 : ] ) return slash_product ( [ space . join ( [ head , word , tail ] ) . strip ( space ) for word in alternatives ] ) | Return a list of all possible meanings of a phrase containing slashes | 291 | 13 |
5,408 | def create_header ( coord , radius , proj = 'ZEA' , npix = 30 ) : gal = coord . name == 'galactic' values = [ [ "NAXIS" , 2 , ] , [ "NAXIS1" , npix , ] , [ "NAXIS2" , npix , ] , [ "CTYPE1" , 'GLON-%s' % proj if gal else 'RA---%s' % proj ] , [ "CTYPE2" , 'GLAT-%s' % proj if gal else 'DEC--%s' % proj ] , [ "CRPIX1" , npix / 2. + 0.5 , ] , [ "CRPIX2" , npix / 2. + 0.5 , ] , [ "CRVAL1" , coord . l . deg if gal else coord . ra . deg , ] , [ "CRVAL2" , coord . b . deg if gal else coord . dec . deg , ] , [ "CDELT1" , - 3. * radius / npix , ] , [ "CDELT2" , 3. * radius / npix , ] , ] if not gal : values += [ [ 'RADECSYS' , 'FK5' ] , [ 'EQUINOX' , 2000 ] , ] cards = [ pyfits . Card ( * i ) for i in values ] header = pyfits . Header ( cards = cards ) return header | Create a header a new image | 324 | 6 |
5,409 | def word_tokenize ( text ) : for ( regexp , replacement ) in RULES1 : text = sub ( regexp , replacement , text ) # add extra space to make things easier text = " " + text + " " for ( regexp , replacement ) in RULES2 : text = sub ( regexp , replacement , text ) for regexp in CONTRACTIONS : text = sub ( regexp , r"\1 \2 " , text ) # split and return return text . split ( ) | Split string text into word tokens using the Penn Treebank rules | 109 | 12 |
5,410 | def get_postcodedata ( self , postcode , nr , addition = "" , * * params ) : endpoint = 'rest/addresses/%s/%s' % ( postcode , nr ) if addition : endpoint += '/' + addition retValue = self . _API__request ( endpoint , params = params ) # then it should match the houseNumberAdditions if addition and addition . upper ( ) not in [ a . upper ( ) for a in retValue [ 'houseNumberAdditions' ] ] : raise PostcodeError ( "ERRHouseNumberAdditionInvalid" , { "exceptionId" : "ERRHouseNumberAdditionInvalid" , "exception" : "Invalid housenumber addition: '%s'" % retValue [ 'houseNumberAddition' ] , "validHouseNumberAdditions" : retValue [ 'houseNumberAdditions' ] } ) return retValue | get_postcodedata - fetch information for postcode . | 195 | 12 |
5,411 | def get_signalcheck ( self , sar , * * params ) : params = sar endpoint = 'rest/signal/check' # The 'sar'-request dictionary should be sent as valid JSON data, so # we need to convert it to JSON # when we construct the request in API.request retValue = self . _API__request ( endpoint , 'POST' , params = params , convJSON = True ) return retValue | get_signalcheck - perform a signal check . | 92 | 11 |
5,412 | def __request ( self , endpoint , method = 'GET' , params = None , convJSON = False ) : url = '%s/%s' % ( self . api_url , endpoint ) method = method . lower ( ) params = params or { } if convJSON : params = json . dumps ( params ) func = getattr ( self . client , method ) request_args = { } if method == 'get' : request_args [ 'params' ] = params else : request_args [ 'data' ] = params try : # Normally some valid HTTP-response will be the case # if not some exception regarding the request / connection has # occurred # this will be one of the exceptions of the request module # if so, we will a PostcodeError exception and pass the request # exception message response = func ( url , * * request_args ) except requests . RequestException as e : raise PostcodeError ( "ERRrequest" , { "exception" : e . __doc__ } ) content = response . content . decode ( 'utf-8' ) content = json . loads ( content ) if response . status_code == 200 : return content # Errors, otherwise we did not get here ... if 'exceptionId' in content : raise PostcodeError ( content [ 'exceptionId' ] , content ) raise PostcodeError ( "UnknownExceptionFromPostcodeNl" ) | request - Returns dict of response from postcode . nl API . | 297 | 14 |
5,413 | def regression_and_plot ( x , y = None ) : if y is None : y = x x = range ( len ( x ) ) if not isinstance ( x [ 0 ] , ( float , int , np . float64 , np . float32 ) ) : x = [ row [ 0 ] for row in x ] A = np . vstack ( [ np . array ( x ) , np . ones ( len ( x ) ) ] ) . T fit = np . linalg . lstsq ( A , y , rcond = None ) # if fit is None: # fit = [(1, 0), None, None, None] poly = fit [ 0 ] [ 0 ] , fit [ 0 ] [ - 1 ] poly = regressionplot ( x , y , poly ) return poly | Fit a line to the x y data supplied and plot it along with teh raw samples | 170 | 18 |
5,414 | def scatmat ( df , category = None , colors = 'rgob' , num_plots = 4 , num_topics = 100 , num_columns = 4 , show = False , block = False , data_path = DATA_PATH , save = False , verbose = 1 ) : if category is None : category = list ( df . columns ) [ - 1 ] if isinstance ( category , ( str , bytes , int ) ) and category in df . columns : category = df [ category ] else : category = pd . Series ( category ) suffix = '{}x{}' . format ( * list ( df . shape ) ) # suffix = compose_suffix(len(df), num_topics, save) # save = bool(save) for i in range ( min ( num_plots * num_columns , num_topics ) / num_plots ) : scatter_matrix ( df [ df . columns [ i * num_columns : ( i + 1 ) * num_columns ] ] , marker = '+' , c = [ colors [ int ( x ) % len ( colors ) ] for x in category . values ] , figsize = ( 18 , 12 ) ) if save : name = 'scatmat_topics_{}-{}.jpg' . format ( i * num_columns , ( i + 1 ) * num_columns ) + suffix plt . savefig ( os . path . join ( data_path , name + '.jpg' ) ) if show : if block : plt . show ( ) else : plt . show ( block = False ) | Scatter plot with colored markers depending on the discrete values in a category column | 352 | 15 |
5,415 | def point_cloud ( df , columns = [ 0 , 1 , 2 ] ) : df = df if isinstance ( df , pd . DataFrame ) else pd . DataFrame ( df ) if not all ( c in df . columns for c in columns ) : columns = list ( df . columns ) [ : 3 ] fig = plt . figure ( ) ax = fig . add_subplot ( 111 , projection = '3d' ) # noqa Axes3D . scatter ( * [ df [ columns [ i ] ] for i in range ( 3 ) ] , zdir = 'z' , s = 20 , c = None , depthshade = True ) return ax | 3 - D Point cloud for plotting things like mesh models of horses ; ) | 146 | 15 |
5,416 | def show ( self , block = False ) : try : plt . show ( block = block ) except ValueError : plt . show ( ) | Display the last image drawn | 31 | 5 |
5,417 | def save ( self , filename ) : plt . savefig ( filename , fig = self . fig , facecolor = 'black' , edgecolor = 'black' ) | save colormap to file | 36 | 6 |
5,418 | def getp ( self , name ) : name = self . _mapping . get ( name , name ) return self . params [ name ] | Get the named parameter . | 30 | 5 |
5,419 | def readColorLUT ( infile , distance_modulus , mag_1 , mag_2 , mag_err_1 , mag_err_2 ) : reader = pyfits . open ( infile ) distance_modulus_array = reader [ 'DISTANCE_MODULUS' ] . data . field ( 'DISTANCE_MODULUS' ) if not numpy . any ( numpy . fabs ( distance_modulus_array - distance_modulus ) < 1.e-3 ) : logger . warning ( "Distance modulus %.2f not available in file %s" % ( distance_modulus , infile ) ) logger . warning ( ' available distance moduli:' + str ( distance_modulus_array ) ) return False distance_modulus_key = '%.2f' % ( distance_modulus_array [ numpy . argmin ( numpy . fabs ( distance_modulus_array - distance_modulus ) ) ] ) bins_mag_err = reader [ 'BINS_MAG_ERR' ] . data . field ( 'BINS_MAG_ERR' ) bins_mag_1 = reader [ 'BINS_MAG_1' ] . data . field ( 'BINS_MAG_1' ) bins_mag_2 = reader [ 'BINS_MAG_2' ] . data . field ( 'BINS_MAG_2' ) # Note that magnitude uncertainty is always assigned by rounding up, is this the right thing to do? index_mag_err_1 = numpy . clip ( numpy . digitize ( mag_err_1 , bins_mag_err ) - 1 , 0 , len ( bins_mag_err ) - 2 ) index_mag_err_2 = numpy . clip ( numpy . digitize ( mag_err_2 , bins_mag_err ) - 1 , 0 , len ( bins_mag_err ) - 2 ) u_color = numpy . zeros ( len ( mag_1 ) ) for index_mag_err_1_select in range ( 0 , len ( bins_mag_err ) - 1 ) : for index_mag_err_2_select in range ( 0 , len ( bins_mag_err ) - 1 ) : cut = numpy . logical_and ( index_mag_err_1 == index_mag_err_1_select , index_mag_err_2 == index_mag_err_2_select ) if numpy . sum ( cut ) < 1 : continue histo = reader [ distance_modulus_key ] . data . field ( '%i%i' % ( index_mag_err_1_select , index_mag_err_2_select ) ) u_color [ cut ] = ugali . utils . binning . take2D ( histo , mag_2 [ cut ] , mag_1 [ cut ] , bins_mag_2 , bins_mag_1 ) reader . close ( ) return u_color | Take in a color look - up table and return the signal color evaluated for each object . Consider making the argument a Catalog object rather than magnitudes and uncertainties . | 655 | 32 |
5,420 | def auto_memoize ( func ) : @ wraps ( func ) def wrapper ( * args ) : inst = args [ 0 ] inst . _memoized_values = getattr ( inst , '_memoized_values' , { } ) key = ( func , args [ 1 : ] ) if key not in inst . _memoized_values : inst . _memoized_values [ key ] = func ( * args ) return inst . _memoized_values [ key ] return wrapper | Based on django . util . functional . memoize . Automatically memoizes instace methods for the lifespan of an object . Only works with methods taking non - keword arguments . Note that the args to the function must be usable as dictionary keys . Also the first argument MUST be self . This decorator will not work for functions or class methods only object methods . | 109 | 74 |
5,421 | def best_fit ( li , value ) : index = min ( bisect_left ( li , value ) , len ( li ) - 1 ) if index in ( 0 , len ( li ) ) : return index if li [ index ] - value < value - li [ index - 1 ] : return index else : return index - 1 | For a sorted list li returns the closest item to value | 70 | 11 |
5,422 | def proj4_to_epsg ( projection ) : def make_definition ( value ) : return { x . strip ( ) . lower ( ) for x in value . split ( '+' ) if x } # Use the EPSG in the definition if available match = EPSG_RE . search ( projection . srs ) if match : return int ( match . group ( 1 ) ) # Otherwise, try to look up the EPSG from the pyproj data file pyproj_data_dir = os . path . join ( os . path . dirname ( pyproj . __file__ ) , 'data' ) pyproj_epsg_file = os . path . join ( pyproj_data_dir , 'epsg' ) if os . path . exists ( pyproj_epsg_file ) : definition = make_definition ( projection . srs ) f = open ( pyproj_epsg_file , 'r' ) for line in f . readlines ( ) : match = PYPROJ_EPSG_FILE_RE . search ( line ) if match : file_definition = make_definition ( match . group ( 2 ) ) if definition == file_definition : return int ( match . group ( 1 ) ) return None | Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails | 273 | 20 |
5,423 | def wkt_to_proj4 ( wkt ) : srs = osgeo . osr . SpatialReference ( ) srs . ImportFromWkt ( wkt ) return pyproj . Proj ( str ( srs . ExportToProj4 ( ) ) ) | Converts a well - known text string to a pyproj . Proj object | 62 | 17 |
5,424 | def proj4_to_wkt ( projection ) : srs = osgeo . osr . SpatialReference ( ) srs . ImportFromProj4 ( projection . srs ) return srs . ExportToWkt ( ) | Converts a pyproj . Proj object to a well - known text string | 52 | 17 |
5,425 | def project_geometry ( geometry , source , target ) : project = partial ( pyproj . transform , source , target ) return transform ( project , geometry ) | Projects a shapely geometry object from the source to the target projection . | 34 | 15 |
5,426 | def _load ( self , config ) : if isstring ( config ) : self . filename = config params = yaml . load ( open ( config ) ) elif isinstance ( config , Config ) : # This is the copy constructor... self . filename = config . filename params = copy . deepcopy ( config ) elif isinstance ( config , dict ) : params = copy . deepcopy ( config ) elif config is None : params = { } else : raise Exception ( 'Unrecognized input' ) return params | Load this config from an existing config | 109 | 7 |
5,427 | def _validate ( self ) : # This could be done with a default config # Check that specific keys exist sections = odict ( [ ( 'catalog' , [ 'dirname' , 'basename' , 'lon_field' , 'lat_field' , 'objid_field' , 'mag_1_band' , 'mag_1_field' , 'mag_err_1_field' , 'mag_2_band' , 'mag_2_field' , 'mag_err_2_field' , ] ) , ( 'mask' , [ ] ) , ( 'coords' , [ 'nside_catalog' , 'nside_mask' , 'nside_likelihood' , 'nside_pixel' , 'roi_radius' , 'roi_radius_annulus' , 'roi_radius_interior' , 'coordsys' , ] ) , ( 'likelihood' , [ ] ) , ( 'output' , [ ] ) , ( 'batch' , [ ] ) , ] ) keys = np . array ( list ( sections . keys ( ) ) ) found = np . in1d ( keys , list ( self . keys ( ) ) ) if not np . all ( found ) : msg = 'Missing sections: ' + str ( keys [ ~ found ] ) raise Exception ( msg ) for section , keys in sections . items ( ) : keys = np . array ( keys ) found = np . in1d ( keys , list ( self [ section ] . keys ( ) ) ) if not np . all ( found ) : msg = 'Missing keys in %s: ' % ( section ) + str ( keys [ ~ found ] ) raise Exception ( msg ) | Enforce some structure to the config file | 374 | 8 |
5,428 | def _formatFilepaths ( self ) : likedir = self [ 'output' ] [ 'likedir' ] self . likefile = join ( likedir , self [ 'output' ] [ 'likefile' ] ) self . mergefile = join ( likedir , self [ 'output' ] [ 'mergefile' ] ) self . roifile = join ( likedir , self [ 'output' ] [ 'roifile' ] ) searchdir = self [ 'output' ] [ 'searchdir' ] self . labelfile = join ( searchdir , self [ 'output' ] [ 'labelfile' ] ) self . objectfile = join ( searchdir , self [ 'output' ] [ 'objectfile' ] ) self . assocfile = join ( searchdir , self [ 'output' ] [ 'assocfile' ] ) self . candfile = join ( searchdir , self [ 'output' ] [ 'candfile' ] ) mcmcdir = self [ 'output' ] [ 'mcmcdir' ] self . mcmcfile = join ( mcmcdir , self [ 'output' ] [ 'mcmcfile' ] ) | Join dirnames and filenames from config . | 256 | 10 |
5,429 | def write ( self , filename ) : ext = os . path . splitext ( filename ) [ 1 ] writer = open ( filename , 'w' ) if ext == '.py' : writer . write ( pprint . pformat ( self ) ) elif ext == '.yaml' : writer . write ( yaml . dump ( self ) ) else : writer . close ( ) raise Exception ( 'Unrecognized config format: %s' % ext ) writer . close ( ) | Write a copy of this config object . | 102 | 8 |
5,430 | def getFilenames ( self , pixels = None ) : logger . debug ( "Getting filenames..." ) if pixels is None : return self . filenames else : return self . filenames [ np . in1d ( self . filenames [ 'pix' ] , pixels ) ] | Return the requested filenames . | 65 | 7 |
5,431 | def superpixel ( subpix , nside_subpix , nside_superpix ) : if nside_subpix == nside_superpix : return subpix theta , phi = hp . pix2ang ( nside_subpix , subpix ) return hp . ang2pix ( nside_superpix , theta , phi ) | Return the indices of the super - pixels which contain each of the sub - pixels . | 84 | 17 |
5,432 | def ud_grade_ipix ( ipix , nside_in , nside_out , nest = False ) : if nside_in == nside_out : return ipix elif nside_in < nside_out : return u_grade_ipix ( ipix , nside_in , nside_out , nest ) elif nside_in > nside_out : return d_grade_ipix ( ipix , nside_in , nside_out , nest ) | Upgrade or degrade resolution of a pixel list . | 111 | 9 |
5,433 | def index_pix_in_pixels ( pix , pixels , sort = False , outside = - 1 ) : # ADW: Not really safe to set index = -1 (accesses last entry); # -np.inf would be better, but breaks other code... # ADW: Are the pixels always sorted? Is there a quick way to check? if sort : pixels = np . sort ( pixels ) # Assumes that 'pixels' is pre-sorted, otherwise...??? index = np . searchsorted ( pixels , pix ) if np . isscalar ( index ) : if not np . in1d ( pix , pixels ) . any ( ) : index = outside else : # Find objects that are outside the pixels index [ ~ np . in1d ( pix , pixels ) ] = outside return index | Find the indices of a set of pixels into another set of pixels . !!! ASSUMES SORTED PIXELS !!! | 178 | 27 |
5,434 | def index_lonlat_in_pixels ( lon , lat , pixels , nside , sort = False , outside = - 1 ) : pix = ang2pix ( nside , lon , lat ) return index_pix_in_pixels ( pix , pixels , sort , outside ) | Find the indices of a set of angles into a set of pixels | 67 | 13 |
5,435 | def header_odict ( nside , nest = False , coord = None , partial = True ) : hdr = odict ( [ ] ) hdr [ 'PIXTYPE' ] = odict ( [ ( 'name' , 'PIXTYPE' ) , ( 'value' , 'HEALPIX' ) , ( 'comment' , 'HEALPIX pixelisation' ) ] ) ordering = 'NEST' if nest else 'RING' hdr [ 'ORDERING' ] = odict ( [ ( 'name' , 'ORDERING' ) , ( 'value' , ordering ) , ( 'comment' , 'Pixel ordering scheme, either RING or NESTED' ) ] ) hdr [ 'NSIDE' ] = odict ( [ ( 'name' , 'NSIDE' ) , ( 'value' , nside ) , ( 'comment' , 'Resolution parameter of HEALPIX' ) ] ) if coord : hdr [ 'COORDSYS' ] = odict ( [ ( 'name' , 'COORDSYS' ) , ( 'value' , coord ) , ( 'comment' , 'Ecliptic, Galactic or Celestial (equatorial)' ) ] ) if not partial : hdr [ 'FIRSTPIX' ] = odict ( [ ( 'name' , 'FIRSTPIX' ) , ( 'value' , 0 ) , ( 'comment' , 'First pixel # (0 based)' ) ] ) hdr [ 'LASTPIX' ] = odict ( [ ( 'name' , 'LASTPIX' ) , ( 'value' , hp . nside2npix ( nside ) - 1 ) , ( 'comment' , 'Last pixel # (0 based)' ) ] ) hdr [ 'INDXSCHM' ] = odict ( [ ( 'name' , 'INDXSCHM' ) , ( 'value' , 'EXPLICIT' if partial else 'IMPLICIT' ) , ( 'comment' , 'Indexing: IMPLICIT or EXPLICIT' ) ] ) hdr [ 'OBJECT' ] = odict ( [ ( 'name' , 'OBJECT' ) , ( 'value' , 'PARTIAL' if partial else 'FULLSKY' ) , ( 'comment' , 'Sky coverage, either FULLSKY or PARTIAL' ) ] ) return hdr | Mimic the healpy header keywords . | 522 | 9 |
5,436 | def write_partial_map ( filename , data , nside , coord = None , nest = False , header = None , dtype = None , * * kwargs ) : # ADW: Do we want to make everything uppercase? if isinstance ( data , dict ) : names = list ( data . keys ( ) ) else : names = data . dtype . names if 'PIXEL' not in names : msg = "'PIXEL' column not found." raise ValueError ( msg ) hdr = header_odict ( nside = nside , coord = coord , nest = nest ) fitshdr = fitsio . FITSHDR ( list ( hdr . values ( ) ) ) if header is not None : for k , v in header . items ( ) : fitshdr . add_record ( { 'name' : k , 'value' : v } ) logger . info ( "Writing %s" % filename ) fitsio . write ( filename , data , extname = 'PIX_DATA' , header = fitshdr , clobber = True ) | Partial HEALPix maps are used to efficiently store maps of the sky by only writing out the pixels that contain data . | 234 | 26 |
5,437 | def merge_likelihood_headers ( filenames , outfile ) : filenames = np . atleast_1d ( filenames ) ext = 'PIX_DATA' nside = fitsio . read_header ( filenames [ 0 ] , ext = ext ) [ 'LKDNSIDE' ] keys = [ 'STELLAR' , 'NINSIDE' , 'NANNULUS' ] data_dict = odict ( PIXEL = [ ] ) for k in keys : data_dict [ k ] = [ ] for i , filename in enumerate ( filenames ) : logger . debug ( '(%i/%i) %s' % ( i + 1 , len ( filenames ) , filename ) ) header = fitsio . read_header ( filename , ext = ext ) data_dict [ 'PIXEL' ] . append ( header [ 'LKDPIX' ] ) for key in keys : data_dict [ key ] . append ( header [ key ] ) del header data_dict [ 'PIXEL' ] = np . array ( data_dict [ 'PIXEL' ] , dtype = int ) for key in keys : data_dict [ key ] = np . array ( data_dict [ key ] , dtype = 'f4' ) #import pdb; pdb.set_trace() write_partial_map ( outfile , data_dict , nside ) return data_dict | Merge header information from likelihood files . | 317 | 8 |
5,438 | def _convert_number ( self , number ) : number = float ( number ) return int ( number ) if number . is_integer ( ) else float ( number ) | Converts a number to float or int as appropriate | 36 | 10 |
5,439 | def do_results ( args ) : config , name , label , coord = args filenames = make_filenames ( config , label ) srcfile = filenames [ 'srcfile' ] samples = filenames [ 'samfile' ] if not exists ( srcfile ) : logger . warning ( "Couldn't find %s; skipping..." % srcfile ) return if not exists ( samples ) : logger . warning ( "Couldn't find %s; skipping..." % samples ) return logger . info ( "Writing %s..." % srcfile ) from ugali . analysis . results import write_results write_results ( srcfile , config , srcfile , samples ) | Write the results output file | 145 | 5 |
5,440 | def do_membership ( args ) : config , name , label , coord = args filenames = make_filenames ( config , label ) srcfile = filenames [ 'srcfile' ] memfile = filenames [ 'memfile' ] logger . info ( "Writing %s..." % memfile ) from ugali . analysis . loglike import write_membership write_membership ( memfile , config , srcfile , section = 'source' ) | Write the membership output file | 102 | 5 |
5,441 | def do_plot ( args ) : import ugali . utils . plotting import pylab as plt config , name , label , coord = args filenames = make_filenames ( config , label ) srcfile = filenames [ 'srcfile' ] samfile = filenames [ 'samfile' ] memfile = filenames [ 'memfile' ] if not exists ( srcfile ) : logger . warning ( "Couldn't find %s; skipping..." % srcfile ) return if not exists ( samfile ) : logger . warning ( "Couldn't find %s; skipping..." % samfile ) return config = ugali . utils . config . Config ( config ) burn = config [ 'mcmc' ] [ 'nburn' ] * config [ 'mcmc' ] [ 'nwalkers' ] source = ugali . analysis . source . Source ( ) source . load ( srcfile , section = 'source' ) outfile = samfile . replace ( '.npy' , '.png' ) ugali . utils . plotting . plotTriangle ( srcfile , samfile , burn = burn ) logger . info ( " Writing %s..." % outfile ) plt . savefig ( outfile , bbox_inches = 'tight' , dpi = 60 ) plt . close ( ) plotter = ugali . utils . plotting . SourcePlotter ( source , config , radius = 0.5 ) data = fitsio . read ( memfile , trim_strings = True ) if exists ( memfile ) else None if data is not None : plt . figure ( ) kernel , isochrone = source . kernel , source . isochrone ugali . utils . plotting . plotMembership ( config , data , kernel , isochrone ) outfile = samfile . replace ( '.npy' , '_mem.png' ) logger . info ( " Writing %s..." % outfile ) plt . savefig ( outfile , bbox_inches = 'tight' , dpi = 60 ) plt . close ( ) plotter . plot6 ( data ) outfile = samfile . replace ( '.npy' , '_6panel.png' ) logger . info ( " Writing %s..." % outfile ) plt . savefig ( outfile , bbox_inches = 'tight' , dpi = 60 ) outfile = samfile . replace ( '.npy' , '_6panel.pdf' ) logger . info ( " Writing %s..." % outfile ) plt . savefig ( outfile , bbox_inches = 'tight' , dpi = 60 ) plt . close ( ) try : title = name plotter . plot4 ( ) outfile = samfile . replace ( '.npy' , '_4panel.png' ) logger . info ( " Writing %s..." % outfile ) plt . suptitle ( title ) plt . savefig ( outfile , bbox_inches = 'tight' , dpi = 60 ) plt . close ( ) except : logger . warning ( " Failed to create plotter.plot4()" ) | Create plots of mcmc output | 684 | 7 |
5,442 | def parse ( self , * args ) : if isinstance ( self . dictionary , dict ) : return self . dictionary raise self . subparserException ( "Argument passed to Dictionary SubParser is not a dict: %s" % type ( self . dictionary ) ) | Return our initialized dictionary arguments . | 55 | 6 |
5,443 | def _caches_dicts ( self ) : qs = ( self . get_query_set ( ) if django . VERSION < ( 1 , 6 ) else self . get_queryset ( ) ) variants_dict = self . _get_variants_dict ( qs ) cache . set ( VARIANTS_DICT_CACHE_KEY , variants_dict ) replace_dict = self . _get_replace_dict ( qs ) cache . set ( REPLACE_DICT_CACHE_KEY , replace_dict ) return variants_dict , replace_dict | Caches variants_dict and replace_dict in a single database hit . | 130 | 15 |
5,444 | def translate_exception ( exc , kwargs ) : error = exc . response [ 'Error' ] error . setdefault ( 'Message' , '' ) err_class = EXC . get ( error [ 'Code' ] , DynamoDBError ) return err_class ( exc . response [ 'ResponseMetadata' ] [ 'HTTPStatusCode' ] , exc_info = sys . exc_info ( ) , args = pformat ( kwargs ) , * * error ) | Translate a botocore . exceptions . ClientError into a dynamo3 error | 103 | 17 |
5,445 | def re_raise ( self ) : if self . exc_info is not None : six . reraise ( type ( self ) , self , self . exc_info [ 2 ] ) else : raise self | Raise this exception with the original traceback | 43 | 9 |
5,446 | def generate_lines ( text , ext = [ '.txt' , '.md' , '.rst' , '.asciidoc' , '.asc' ] ) : if isinstance ( text , basestring ) : if len ( text ) <= 256 : if os . path . isfile ( text ) and os . path . splitext ( text ) [ - 1 ] . lower ( ) in ext : return open ( text ) elif os . path . isdir ( text ) : return chain . from_iterable ( generate_lines ( stat [ 'path' ] ) for stat in find_files ( text , ext = ext ) ) else : return ( line for line in Split ( text = text ) ) else : return Split ( text = text ) return chain . from_iterable ( generate_lines ( obj ) for obj in text ) | r Yield text one line at a time from from a single file path files in a directory or a text string | 180 | 23 |
5,447 | def add ( self , now , num ) : if num == 0 : return self . points . append ( ( now , num ) ) | Add a timestamp and date to the data | 28 | 8 |
5,448 | def value ( self ) : now = time . time ( ) cutoff = now - self . window while self . points and self . points [ 0 ] [ 0 ] < cutoff : self . points . pop ( 0 ) return sum ( [ p [ 1 ] for p in self . points ] ) | Get the summation of all non - expired points | 61 | 10 |
5,449 | def get_consumed ( self , key ) : if key not in self . _consumed : self . _consumed [ key ] = { 'read' : DecayingCapacityStore ( ) , 'write' : DecayingCapacityStore ( ) , } return self . _consumed [ key ] | Getter for a consumed capacity storage dict | 65 | 8 |
5,450 | def on_capacity ( self , connection , command , query_kwargs , response , capacity ) : now = time . time ( ) args = ( connection , command , query_kwargs , response , capacity ) # Check total against the total_cap self . _wait ( args , now , self . total_cap , self . _total_consumed , capacity . total ) # Increment table consumed capacity & check it if capacity . tablename in self . table_caps : table_cap = self . table_caps [ capacity . tablename ] else : table_cap = self . default_cap consumed_history = self . get_consumed ( capacity . tablename ) if capacity . table_capacity is not None : self . _wait ( args , now , table_cap , consumed_history , capacity . table_capacity ) # The local index consumed capacity also counts against the table if capacity . local_index_capacity is not None : for consumed in six . itervalues ( capacity . local_index_capacity ) : self . _wait ( args , now , table_cap , consumed_history , consumed ) # Increment global indexes # check global indexes against the table+index cap or default gic = capacity . global_index_capacity if gic is not None : for index_name , consumed in six . iteritems ( gic ) : full_name = capacity . tablename + ':' + index_name if index_name in table_cap : index_cap = table_cap [ index_name ] elif full_name in self . table_caps : index_cap = self . table_caps [ full_name ] else : # If there's no specified capacity for the index, # use the cap on the table index_cap = table_cap consumed_history = self . get_consumed ( full_name ) self . _wait ( args , now , index_cap , consumed_history , consumed ) | Hook that runs in response to a returned capacity event | 413 | 11 |
5,451 | def _wait ( self , args , now , cap , consumed_history , consumed_capacity ) : for key in [ 'read' , 'write' ] : if key in cap and cap [ key ] > 0 : consumed_history [ key ] . add ( now , consumed_capacity [ key ] ) consumed = consumed_history [ key ] . value if consumed > 0 and consumed >= cap [ key ] : seconds = math . ceil ( float ( consumed ) / cap [ key ] ) LOG . debug ( "Rate limited throughput exceeded. Sleeping " "for %d seconds." , seconds ) if callable ( self . callback ) : callback_args = args + ( seconds , ) if self . callback ( * callback_args ) : continue time . sleep ( seconds ) | Check the consumed capacity against the limit and sleep | 161 | 9 |
5,452 | def create_case ( self , name , email , subject , description , businessImpact , priority , phone ) : if not ( '@' in parseaddr ( email ) [ 1 ] ) : raise ValueError ( 'invalid email: {}' . format ( email ) ) if '' == name or name is None : raise ValueError ( 'empty name' ) if '' == subject or subject is None : raise ValueError ( 'empty subject' ) if '' == description or description is None : raise ValueError ( 'empty description' ) if '' == businessImpact or businessImpact is None : raise ValueError ( 'empty business impact' ) if priority is None : raise ValueError ( 'Ensure the priority is from the set of ' 'known priorities' ) if '' == phone or phone is None : raise ValueError ( 'empty phone' ) try : r = requests . post ( self . url , data = { 'orgid' : self . orgId , 'recordType' : self . recordType , 'name' : name , 'email' : email , 'subject' : subject , 'description' : description , self . BUSINESS_IMPACT : businessImpact , 'priority' : priority , 'phone' : phone , 'external' : 1 } , timeout = self . timeout ) r . raise_for_status ( ) except Timeout : message = 'Request timed out: {url} timeout: {timeout}' message = message . format ( url = self . url , timeout = self . timeout ) log . error ( message ) raise ServerError ( message ) except RequestException as err : log . info ( 'cannot create case: {}' . format ( err ) ) raise ServerError ( 'cannot create case: {}' . format ( err ) ) | Send a case creation to SalesForces to create a ticket . | 376 | 13 |
5,453 | def get_cumulative_spend ( key ) : query = ( 'ROUND(SUM(total_ex_vat), 2) AS total ' 'FROM {table} ' 'WHERE date <= "{year}-{month:02}-01" ' 'AND lot="{lot}" ' 'AND customer_sector="{sector}" ' 'AND supplier_type="{sme_large}"' . format ( table = _RAW_SALES_TABLE , year = key . year , month = key . month , lot = key . lot , sector = key . sector , sme_large = key . sme_large ) ) logging . debug ( query ) result = scraperwiki . sqlite . select ( query ) logging . debug ( result ) value = result [ 0 ] [ 'total' ] return float ( result [ 0 ] [ 'total' ] ) if value is not None else 0.0 | Get the sum of spending for this category up to and including the given month . | 198 | 16 |
5,454 | def plot ( self , value = None , pixel = None ) : # DEPRECATED import ugali . utils . plotting map_roi = np . array ( hp . UNSEEN * np . ones ( hp . nside2npix ( self . config . params [ 'coords' ] [ 'nside_pixel' ] ) ) ) if value is None : #map_roi[self.pixels] = ugali.utils.projector.angsep(self.lon, self.lat, self.centers_lon, self.centers_lat) map_roi [ self . pixels ] = 1 map_roi [ self . pixels_annulus ] = 0 map_roi [ self . pixels_target ] = 2 elif value is not None and pixel is None : map_roi [ self . pixels ] = value elif value is not None and pixel is not None : map_roi [ pixel ] = value else : logger . error ( "Can't parse input" ) ugali . utils . plotting . zoomedHealpixMap ( 'Region of Interest' , map_roi , self . lon , self . lat , self . config . params [ 'coords' ] [ 'roi_radius' ] ) | Plot the ROI | 280 | 4 |
5,455 | def inPixels ( self , lon , lat , pixels ) : nside = self . config . params [ 'coords' ] [ 'nside_pixel' ] return ugali . utils . healpix . in_pixels ( lon , lat , pixels , nside ) | Function for testing if coordintes in set of ROI pixels . | 64 | 14 |
5,456 | def getCatalogPixels ( self ) : filenames = self . config . getFilenames ( ) nside_catalog = self . config . params [ 'coords' ] [ 'nside_catalog' ] nside_pixel = self . config . params [ 'coords' ] [ 'nside_pixel' ] # All possible catalog pixels spanned by the ROI superpix = ugali . utils . skymap . superpixel ( self . pixels , nside_pixel , nside_catalog ) superpix = np . unique ( superpix ) # Only catalog pixels that exist in catalog files pixels = np . intersect1d ( superpix , filenames [ 'pix' ] . compressed ( ) ) return pixels | Return the catalog pixels spanned by this ROI . | 166 | 11 |
5,457 | def schema ( self , hash_key ) : key_schema = [ hash_key . hash_schema ( ) ] if self . range_key is not None : key_schema . append ( self . range_key . range_schema ( ) ) schema_data = { 'IndexName' : self . name , 'KeySchema' : key_schema , 'Projection' : { 'ProjectionType' : self . projection_type , } } if self . include_fields is not None : schema_data [ 'Projection' ] [ 'NonKeyAttributes' ] = self . include_fields return schema_data | Create the index schema | 138 | 4 |
5,458 | def all ( cls , name , hash_key , range_key = None , throughput = None ) : return cls ( cls . ALL , name , hash_key , range_key , throughput = throughput ) | Create an index that projects all attributes | 46 | 7 |
5,459 | def keys ( cls , name , hash_key , range_key = None , throughput = None ) : return cls ( cls . KEYS , name , hash_key , range_key , throughput = throughput ) | Create an index that projects only key attributes | 47 | 8 |
5,460 | def schema ( self ) : schema_data = super ( GlobalIndex , self ) . schema ( self . hash_key ) schema_data [ 'ProvisionedThroughput' ] = self . throughput . schema ( ) return schema_data | Construct the schema definition for this index | 50 | 7 |
5,461 | def from_response ( cls , response ) : hash_key = None range_key = None # KeySchema may not be in the response if the TableStatus is DELETING. if 'KeySchema' in response : attrs = dict ( ( ( d [ 'AttributeName' ] , DynamoKey ( d [ 'AttributeName' ] , d [ 'AttributeType' ] ) ) for d in response [ 'AttributeDefinitions' ] ) ) hash_key = attrs [ response [ 'KeySchema' ] [ 0 ] [ 'AttributeName' ] ] if len ( response [ 'KeySchema' ] ) > 1 : range_key = attrs [ response [ 'KeySchema' ] [ 1 ] [ 'AttributeName' ] ] indexes = [ ] for idx in response . get ( 'LocalSecondaryIndexes' , [ ] ) : indexes . append ( LocalIndex . from_response ( idx , attrs ) ) global_indexes = [ ] for idx in response . get ( 'GlobalSecondaryIndexes' , [ ] ) : global_indexes . append ( GlobalIndex . from_response ( idx , attrs ) ) table = cls ( name = response [ 'TableName' ] , hash_key = hash_key , range_key = range_key , indexes = indexes , global_indexes = global_indexes , throughput = Throughput . from_response ( response [ 'ProvisionedThroughput' ] ) , status = response [ 'TableStatus' ] , size = response [ 'TableSizeBytes' ] , ) table . response = response return table | Create a Table from returned Dynamo data | 347 | 7 |
5,462 | def serialize ( self ) : if self . action == 'Create' : payload = self . extra [ 'index' ] . schema ( ) else : payload = { 'IndexName' : self . index_name , } if self . action == 'Update' : payload [ 'ProvisionedThroughput' ] = self . extra [ 'throughput' ] . schema ( ) return { self . action : payload } | Get the serialized Dynamo format for the update | 88 | 9 |
5,463 | def instance ( cls , interval = 5 ) : if not cls . _instance : cls . _instance = _Messenger ( interval ) return cls . _instance | Returns existing instance of messenger . If one does not exist it will be created and returned . | 37 | 18 |
5,464 | def send ( self , message , * args , * * kwargs ) : self . _messages . put ( ( message , args , kwargs ) , False ) | Sends provided message to all listeners . Message is only added to queue and will be processed on next tick . | 37 | 22 |
5,465 | def subscribe ( self , message , handler ) : with self . _lock : ref = WeakCallable ( handler , self . _on_collect ) self . _subscribers [ message ] . append ( ref ) | Adds hander for specified message . | 45 | 7 |
5,466 | def unsubscribe ( self , message , handler ) : with self . _lock : self . _subscribers [ message ] . remove ( WeakCallable ( handler ) ) | Removes handler from message listeners . | 36 | 7 |
5,467 | def _execute ( self , sender , event_args ) : with self . _lock : while not self . _messages . empty ( ) : msg , args , kwargs = self . _messages . get ( False ) for subscriber in self . _subscribers [ msg ] : try : subscriber ( * args , * * kwargs ) except weakref . ReferenceError : # Reference to handler is lost and it is OK to silence it pass | Event handler for timer that processes all queued messages . | 96 | 11 |
5,468 | def emit ( self , * args , * * kwargs ) : self . _messanger . send ( self , * args , * * kwargs ) | Emits this signal . As result all handlers will be invoked . | 34 | 13 |
5,469 | def RaisePropertyChanged ( self , property_name ) : args = PropertyChangedEventArgs ( property_name ) for handler in self . property_chaged_handlers : handler ( self , args ) | Raises event that property value has changed for provided property name . | 42 | 13 |
5,470 | def walk_level ( path , level = 1 ) : if level is None : level = float ( 'inf' ) path = expand_path ( path ) if os . path . isdir ( path ) : root_level = path . count ( os . path . sep ) for root , dirs , files in os . walk ( path ) : yield root , dirs , files if root . count ( os . path . sep ) >= root_level + level : del dirs [ : ] elif os . path . isfile ( path ) : yield os . path . dirname ( path ) , [ ] , [ os . path . basename ( path ) ] else : raise RuntimeError ( "Can't find a valid folder or file for path {0}" . format ( repr ( path ) ) ) | Like os . walk but takes level kwarg that indicates how deep the recursion will go . | 170 | 20 |
5,471 | def get_stat ( full_path ) : status = { } status [ 'size' ] = os . path . getsize ( full_path ) status [ 'accessed' ] = datetime . datetime . fromtimestamp ( os . path . getatime ( full_path ) ) status [ 'modified' ] = datetime . datetime . fromtimestamp ( os . path . getmtime ( full_path ) ) status [ 'changed_any' ] = datetime . datetime . fromtimestamp ( os . path . getctime ( full_path ) ) # first 3 digits are User, Group, Other permissions: 1=execute,2=write,4=read status [ 'mode' ] = os . stat ( full_path ) . st_mode status [ 'type' ] = get_type ( full_path ) return status | Use python builtin equivalents to unix stat command and return dict containing stat data about a file | 184 | 19 |
5,472 | def split ( config , dirname = 'split' , force = False ) : config = Config ( config ) filenames = config . getFilenames ( ) #healpix = filenames['pix'].compressed() # Check that things are ok basedir , basename = os . path . split ( config [ 'mask' ] [ 'dirname' ] ) #if basename == dirname: # msg = "Input and output directory are the same." # raise Exception(msg) outdir = mkdir ( os . path . join ( basedir , dirname ) ) nside_catalog = config [ 'coords' ] [ 'nside_catalog' ] nside_pixel = config [ 'coords' ] [ 'nside_pixel' ] release = config [ 'data' ] [ 'release' ] . lower ( ) band1 = config [ 'catalog' ] [ 'mag_1_band' ] band2 = config [ 'catalog' ] [ 'mag_2_band' ] # Read the magnitude limits maglimdir = config [ 'maglim' ] [ 'dirname' ] maglimfile_1 = join ( maglimdir , config [ 'maglim' ] [ 'filename_1' ] ) logger . info ( "Reading %s..." % maglimfile_1 ) maglim1 = read_map ( maglimfile_1 ) maglimfile_2 = join ( maglimdir , config [ 'maglim' ] [ 'filename_2' ] ) logger . info ( "Reading %s..." % maglimfile_2 ) maglim2 = read_map ( maglimfile_2 ) # Read the footprint footfile = config [ 'data' ] [ 'footprint' ] logger . info ( "Reading %s..." % footfile ) footprint = read_map ( footfile ) # Output mask names mask1 = os . path . basename ( config [ 'mask' ] [ 'basename_1' ] ) mask2 = os . path . basename ( config [ 'mask' ] [ 'basename_2' ] ) for band , maglim , base in [ ( band1 , maglim1 , mask1 ) , ( band2 , maglim2 , mask2 ) ] : nside_maglim = hp . npix2nside ( len ( maglim ) ) if nside_maglim != nside_pixel : msg = "Mask nside different from pixel nside" logger . warning ( msg ) #raise Exception(msg) pixels = np . nonzero ( maglim > 0 ) [ 0 ] superpix = superpixel ( pixels , nside_maglim , nside_catalog ) healpix = np . unique ( superpix ) for hpx in healpix : outfile = join ( outdir , base ) % hpx if os . path . exists ( outfile ) and not force : logger . warning ( "Found %s; skipping..." % outfile ) continue pix = pixels [ superpix == hpx ] print ( hpx , len ( pix ) ) logger . info ( 'Writing %s...' % outfile ) data = odict ( ) data [ 'PIXEL' ] = pix data [ 'MAGLIM' ] = maglim [ pix ] . astype ( 'f4' ) data [ 'FRACDET' ] = footprint [ pix ] . astype ( 'f4' ) ugali . utils . healpix . write_partial_map ( outfile , data , nside_pixel ) | Take a pre - existing maglim map and divide it into chunks consistent with the catalog pixels . | 774 | 19 |
5,473 | def run ( self , field = None , simple = False , force = False ) : if field is None : fields = [ 1 , 2 ] else : fields = [ field ] for filenames in self . filenames . compress ( ~ self . filenames . mask [ 'catalog' ] ) . data : infile = filenames [ 'catalog' ] for f in fields : outfile = filenames [ 'mask_%i' % f ] if os . path . exists ( outfile ) and not force : logger . info ( "Found %s; skipping..." % outfile ) continue pixels , maglims = self . calculate ( infile , f , simple ) logger . info ( "Creating %s" % outfile ) outdir = mkdir ( os . path . dirname ( outfile ) ) data = odict ( ) data [ 'PIXEL' ] = pixels data [ 'MAGLIM' ] = maglims . astype ( 'f4' ) ugali . utils . healpix . write_partial_map ( outfile , data , self . nside_pixel ) | Loop through pixels containing catalog objects and calculate the magnitude limit . This gets a bit convoluted due to all the different pixel resolutions ... | 244 | 25 |
5,474 | def get_variable_set ( self , variable_set , data ) : if data . get ( 'dynamic_layers' ) : variable_set = [ ] # TODO elif data . get ( 'layers' ) : op , layer_ids = data [ 'layers' ] . split ( ':' , 1 ) op = op . lower ( ) layer_ids = [ int ( x ) for x in layer_ids . split ( ',' ) ] if op in ( 'show' , 'include' ) : variable_set = [ x for x in variable_set if x . index in layer_ids ] elif op in ( 'hide' , 'exclude' ) : variable_set = [ x for x in variable_set if x . index not in layer_ids ] elif self . service . render_top_layer_only : variable_set = [ variable_set [ 0 ] ] return variable_set | Filters the given variable set based on request parameters | 202 | 10 |
5,475 | def apply_time_to_configurations ( self , configurations , data ) : time_value = None if data . get ( 'time' ) : time_value = data [ 'time' ] # Only single time values are supported. For extents, just grab the first value if isinstance ( data [ 'time' ] , ( tuple , list ) ) : time_value = time_value [ 0 ] if time_value : for config in configurations : config . set_time_index_from_datetime ( time_value , best_fit = ALLOW_BEST_FIT_TIME_INDEX ) return configurations | Applies the correct time index to configurations | 134 | 8 |
5,476 | def _get_form_defaults ( self ) : return { 'response_format' : 'html' , 'bbox' : self . service . full_extent , 'size' : '400,400' , 'dpi' : 200 , 'image_projection' : pyproj . Proj ( str ( self . service . projection ) ) , 'bbox_projection' : pyproj . Proj ( str ( self . service . projection ) ) , 'image_format' : 'png' , 'transparent' : True } | Returns default values for the get image form | 121 | 8 |
5,477 | def get_render_configurations ( self , request , * * kwargs ) : data = self . process_form_data ( self . _get_form_defaults ( ) , kwargs ) variable_set = self . get_variable_set ( self . service . variable_set . order_by ( 'index' ) , data ) base_config = ImageConfiguration ( extent = data [ 'bbox' ] , size = data [ 'size' ] , image_format = data [ 'image_format' ] , background_color = TRANSPARENT_BACKGROUND_COLOR if data . get ( 'transparent' ) else DEFAULT_BACKGROUND_COLOR ) return base_config , self . apply_time_to_configurations ( [ RenderConfiguration ( v ) for v in variable_set ] , data ) | Render image interface | 179 | 3 |
5,478 | def _get_form_defaults ( self ) : return { 'response_format' : 'html' , 'geometry_type' : 'esriGeometryPoint' , 'projection' : pyproj . Proj ( str ( self . service . projection ) ) , 'return_geometry' : True , 'maximum_allowable_offset' : 2 , 'geometry_precision' : 3 , 'return_z' : False , 'return_m' : False } | Returns default values for the identify form | 107 | 7 |
5,479 | def get_terms ( self , name , revision = None ) : url = '{}terms/{}' . format ( self . url , name ) if revision : url = '{}?revision={}' . format ( url , revision ) json = make_request ( url , timeout = self . timeout , client = self . _client ) try : # This is always a list of one element. data = json [ 0 ] return Term ( name = data [ 'name' ] , title = data . get ( 'title' ) , revision = data [ 'revision' ] , created_on = datetime . datetime . strptime ( data [ 'created-on' ] , "%Y-%m-%dT%H:%M:%SZ" ) , content = data [ 'content' ] ) except ( KeyError , TypeError , ValueError , IndexError ) as err : log . info ( 'cannot process terms: invalid JSON response: {!r}' . format ( json ) ) raise ServerError ( 'unable to get terms for {}: {}' . format ( name , err ) ) | Retrieve a specific term and condition . | 244 | 8 |
5,480 | def open_dataset ( self , service ) : if not self . dataset : path = os . path . join ( SERVICE_DATA_ROOT , service . data_path ) self . dataset = netCDF4 . Dataset ( path , 'r' ) return self . dataset | Opens and returns the NetCDF dataset associated with a service or returns a previously - opened dataset | 62 | 20 |
5,481 | def _normalize_bbox ( self , bbox , size ) : bbox_ratio = float ( bbox . width ) / float ( bbox . height ) size_ratio = float ( size [ 0 ] ) / float ( size [ 1 ] ) if round ( size_ratio , 4 ) == round ( bbox_ratio , 4 ) : return bbox else : if bbox . height * size_ratio >= bbox . width : diff = bbox . height * size_ratio - bbox . width return BBox ( ( bbox . xmin - diff / 2 , bbox . ymin , bbox . xmax + diff / 2 , bbox . ymax ) , bbox . projection ) else : diff = abs ( bbox . width / size_ratio - bbox . height ) return BBox ( ( bbox . xmin , bbox . ymin - diff / 2 , bbox . xmax , bbox . ymax + diff / 2 ) , bbox . projection ) | Returns this bbox normalized to match the ratio of the given size . | 223 | 14 |
5,482 | def create_response ( self , request , image , content_type ) : return HttpResponse ( content = image , content_type = content_type ) | Returns a response object for the given image . Can be overridden to return different responses . | 33 | 18 |
5,483 | def create_response ( self , request , content , content_type ) : return HttpResponse ( content = content , content_type = content_type ) | Returns a response object for the request . Can be overridden to return different responses . | 33 | 17 |
5,484 | def process_temporary_file ( self , tmp_file ) : #Truncate filename if necessary if len ( tmp_file . filename ) > 100 : base_filename = tmp_file . filename [ : tmp_file . filename . rfind ( "." ) ] tmp_file . filename = "%s.%s" % ( base_filename [ : 99 - len ( tmp_file . extension ) ] , tmp_file . extension ) tmp_file . save ( ) data = { 'uuid' : str ( tmp_file . uuid ) } response = HttpResponse ( json . dumps ( data ) , status = 201 ) response [ 'Content-type' ] = "text/plain" return response | Truncates the filename if necessary saves the model and returns a response | 153 | 14 |
5,485 | def createLabels2D ( self ) : logger . debug ( " Creating 2D labels..." ) self . zmax = np . argmax ( self . values , axis = 1 ) self . vmax = self . values [ np . arange ( len ( self . pixels ) , dtype = int ) , self . zmax ] kwargs = dict ( pixels = self . pixels , values = self . vmax , nside = self . nside , threshold = self . threshold , xsize = self . xsize ) labels , nlabels = CandidateSearch . labelHealpix ( * * kwargs ) self . nlabels = nlabels self . labels = np . repeat ( labels , len ( self . distances ) ) . reshape ( len ( labels ) , len ( self . distances ) ) return self . labels , self . nlabels | 2D labeling at zmax | 185 | 6 |
5,486 | def process_csv ( f ) : reader = unicodecsv . DictReader ( f , encoding = _ENCODING ) for row in reader : month , year = parse_month_year ( row [ 'Return Month' ] ) yield OrderedDict ( [ ( 'customer_name' , row [ 'CustomerName' ] ) , ( 'supplier_name' , row [ 'SupplierName' ] ) , ( 'month' , month ) , ( 'year' , year ) , ( 'date' , datetime . date ( year , month , 1 ) ) , ( 'total_ex_vat' , parse_price ( row [ 'EvidencedSpend' ] ) ) , ( 'lot' , parse_lot_name ( row [ 'LotDescription' ] ) ) , ( 'customer_sector' , parse_customer_sector ( row [ 'Sector' ] ) ) , ( 'supplier_type' , parse_sme_or_large ( row [ 'SME or Large' ] ) ) , ] ) | Take a file - like object and yield OrderedDicts to be inserted into raw spending database . | 231 | 20 |
5,487 | def try_number ( value ) : for cast_function in [ int , float ] : try : return cast_function ( value ) except ValueError : pass raise ValueError ( "Unable to use value as int or float: {0!r}" . format ( value ) ) | Attempt to cast the string value to an int and failing that a float failing that raise a ValueError . | 59 | 21 |
5,488 | def convert_durations ( metric ) : if metric [ 0 ] == 'avgSessionDuration' and metric [ 1 ] : new_metric = ( metric [ 0 ] , metric [ 1 ] * 1000 ) else : new_metric = metric return new_metric | Convert session duration metrics from seconds to milliseconds . | 58 | 10 |
5,489 | def to_datetime ( date_key ) : match = re . search ( r'\d{4}-\d{2}(-\d{2})?' , date_key ) formatter = '%Y-%m' if len ( match . group ( ) ) == 10 : formatter += '-%d' return datetime . strptime ( match . group ( ) , formatter ) . replace ( tzinfo = pytz . UTC ) | Extract the first date from key matching YYYY - MM - DD or YYYY - MM and convert to datetime . | 101 | 27 |
5,490 | def float_to_decimal ( f ) : n , d = f . as_integer_ratio ( ) numerator , denominator = Decimal ( n ) , Decimal ( d ) return DECIMAL_CONTEXT . divide ( numerator , denominator ) | Convert a float to a 38 - precision Decimal | 58 | 11 |
5,491 | def is_dynamo_value ( value ) : if not isinstance ( value , dict ) or len ( value ) != 1 : return False subkey = six . next ( six . iterkeys ( value ) ) return subkey in TYPES_REV | Returns True if the value is a Dynamo - formatted value | 56 | 11 |
5,492 | def encode_set ( dynamizer , value ) : inner_value = next ( iter ( value ) ) inner_type = dynamizer . raw_encode ( inner_value ) [ 0 ] return inner_type + 'S' , [ dynamizer . raw_encode ( v ) [ 1 ] for v in value ] | Encode a set for the DynamoDB format | 69 | 9 |
5,493 | def encode_list ( dynamizer , value ) : encoded_list = [ ] dict ( map ( dynamizer . raw_encode , value ) ) for v in value : encoded_type , encoded_value = dynamizer . raw_encode ( v ) encoded_list . append ( { encoded_type : encoded_value , } ) return 'L' , encoded_list | Encode a list for the DynamoDB format | 80 | 9 |
5,494 | def encode_dict ( dynamizer , value ) : encoded_dict = { } for k , v in six . iteritems ( value ) : encoded_type , encoded_value = dynamizer . raw_encode ( v ) encoded_dict [ k ] = { encoded_type : encoded_value , } return 'M' , encoded_dict | Encode a dict for the DynamoDB format | 73 | 9 |
5,495 | def raw_encode ( self , value ) : if type ( value ) in self . encoders : encoder = self . encoders [ type ( value ) ] return encoder ( self , value ) raise ValueError ( "No encoder for value '%s' of type '%s'" % ( value , type ( value ) ) ) | Run the encoder on a value | 75 | 7 |
5,496 | def encode_keys ( self , keys ) : return dict ( ( ( k , self . encode ( v ) ) for k , v in six . iteritems ( keys ) if not is_null ( v ) ) ) | Run the encoder on a dict of values | 46 | 9 |
5,497 | def maybe_encode_keys ( self , keys ) : ret = { } for k , v in six . iteritems ( keys ) : if is_dynamo_value ( v ) : return keys elif not is_null ( v ) : ret [ k ] = self . encode ( v ) return ret | Same as encode_keys but a no - op if already in Dynamo format | 67 | 15 |
5,498 | def decode_keys ( self , keys ) : return dict ( ( ( k , self . decode ( v ) ) for k , v in six . iteritems ( keys ) ) ) | Run the decoder on a dict of values | 38 | 9 |
5,499 | def decode ( self , dynamo_value ) : type , value = next ( six . iteritems ( dynamo_value ) ) if type == STRING : return value elif type == BINARY : return Binary ( value ) elif type == NUMBER : return Decimal ( value ) elif type == STRING_SET : return set ( value ) elif type == BINARY_SET : return set ( ( Binary ( v ) for v in value ) ) elif type == NUMBER_SET : return set ( ( Decimal ( v ) for v in value ) ) elif type == BOOL : return value elif type == LIST : return [ self . decode ( v ) for v in value ] elif type == MAP : decoded_dict = { } for k , v in six . iteritems ( value ) : decoded_dict [ k ] = self . decode ( v ) return decoded_dict elif type == NULL : return None else : raise TypeError ( "Received unrecognized type %r from dynamo" , type ) | Decode a dynamo value into a python value | 226 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.