idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
5,400 | def sort_strings ( strings , sort_order = None , reverse = False , case_sensitive = False , sort_order_first = True ) : if not case_sensitive : sort_order = tuple ( s . lower ( ) for s in sort_order ) strings = tuple ( s . lower ( ) for s in strings ) prefix_len = max ( len ( s ) for s in sort_order ) def compare ( a ,... | Sort a list of strings according to the provided sorted list of string prefixes |
5,401 | def clean_field_dict ( field_dict , cleaner = str . strip , time_zone = None ) : r d = { } if time_zone is None : tz = DEFAULT_TZ for k , v in viewitems ( field_dict ) : if k == '_state' : continue if isinstance ( v , basestring ) : d [ k ] = cleaner ( str ( v ) ) elif isinstance ( v , ( datetime . datetime , datetime ... | r Normalize field values by stripping whitespace from strings localizing datetimes to a timezone etc |
5,402 | def generate_tuple_batches ( qs , batch_len = 1 ) : num_items , batch = 0 , [ ] for item in qs : if num_items >= batch_len : yield tuple ( batch ) num_items = 0 batch = [ ] num_items += 1 batch += [ item ] if num_items : yield tuple ( batch ) | Iterate through a queryset in batches of length batch_len |
5,403 | def find_count_label ( d ) : for name in COUNT_NAMES : if name in d : return name for name in COUNT_NAMES : if str ( name ) . lower ( ) in d : return name | Find the member of a set that means count or frequency or probability or number of occurrences . |
5,404 | def fuzzy_get_value ( obj , approximate_key , default = None , ** kwargs ) : dict_obj = OrderedDict ( obj ) try : return dict_obj [ list ( dict_obj . keys ( ) ) [ int ( approximate_key ) ] ] except ( ValueError , IndexError ) : pass return fuzzy_get ( dict_obj , approximate_key , key_and_value = False , ** kwargs ) | Like fuzzy_get but assume the obj is dict - like and return the value without the key |
5,405 | def joined_seq ( seq , sep = None ) : r joined_seq = tuple ( seq ) if isinstance ( sep , basestring ) : joined_seq = sep . join ( str ( item ) for item in joined_seq ) return joined_seq | r Join a sequence into a tuple or a concatenated string |
5,406 | def dos_from_table ( table , header = None ) : start_row = 0 if not table : return table if not header : header = table [ 0 ] start_row = 1 header_list = header if header and isinstance ( header , basestring ) : header_list = header . split ( '\t' ) if len ( header_list ) != len ( table [ 0 ] ) : header_list = header .... | Produce dictionary of sequences from sequence of sequences optionally with a header row . |
5,407 | def transposed_lists ( list_of_lists , default = None ) : if default is None or default is [ ] or default is tuple ( ) : default = [ ] elif default is 'None' : default = [ None ] else : default = [ default ] N = len ( list_of_lists ) Ms = [ len ( row ) for row in list_of_lists ] M = max ( Ms ) ans = [ ] for j in range ... | Like numpy . transposed but allows uneven row lengths |
5,408 | def hist_from_counts ( counts , normalize = False , cumulative = False , to_str = False , sep = ',' , min_bin = None , max_bin = None ) : counters = [ dict ( ( i , c ) for i , c in enumerate ( counts ) ) ] intkeys_list = [ [ c for c in counts_dict if ( isinstance ( c , int ) or ( isinstance ( c , float ) and int ( c ) ... | Compute an emprical histogram PMF or CDF in a list of lists |
5,409 | def get_similar ( obj , labels , default = None , min_similarity = 0.5 ) : raise NotImplementedError ( "Unfinished implementation, needs to be in fuzzy_get where list of scores & keywords is sorted." ) labels = listify ( labels ) def not_found ( * args , ** kwargs ) : return 0 min_score = int ( min_similarity * 100 ) f... | Similar to fuzzy_get but allows non - string keys and a list of possible keys |
5,410 | def update_file_ext ( filename , ext = 'txt' , sep = '.' ) : r path , filename = os . path . split ( filename ) if ext and ext [ 0 ] == sep : ext = ext [ 1 : ] return os . path . join ( path , sep . join ( filename . split ( sep ) [ : - 1 if filename . count ( sep ) > 1 else 1 ] + [ ext ] ) ) | r Force the file or path str to end with the indicated extension |
5,411 | def transcode ( infile , outfile = None , incoding = "shift-jis" , outcoding = "utf-8" ) : if not outfile : outfile = os . path . basename ( infile ) + '.utf8' with codecs . open ( infile , "rb" , incoding ) as fpin : with codecs . open ( outfile , "wb" , outcoding ) as fpout : fpout . write ( fpin . read ( ) ) | Change encoding of text file |
5,412 | def dict2obj ( d ) : if isinstance ( d , ( Mapping , list , tuple ) ) : try : d = dict ( d ) except ( ValueError , TypeError ) : return d else : return d obj = Object ( ) for k , v in viewitems ( d ) : obj . __dict__ [ k ] = dict2obj ( v ) return obj | Convert a dict to an object or namespace |
5,413 | def int_pair ( s , default = ( 0 , None ) ) : s = re . split ( r'[^0-9]+' , str ( s ) . strip ( ) ) if len ( s ) and len ( s [ 0 ] ) : if len ( s ) > 1 and len ( s [ 1 ] ) : return ( int ( s [ 0 ] ) , int ( s [ 1 ] ) ) return ( int ( s [ 0 ] ) , default [ 1 ] ) return default | Return the digits to either side of a single non - digit character as a 2 - tuple of integers |
5,414 | def make_float ( s , default = '' , ignore_commas = True ) : r if ignore_commas and isinstance ( s , basestring ) : s = s . replace ( ',' , '' ) try : return float ( s ) except ( IndexError , ValueError , AttributeError , TypeError ) : try : return float ( str ( s ) ) except ValueError : try : return float ( normalize_... | r Coerce a string into a float |
5,415 | def normalize_names ( names ) : if isinstance ( names , basestring ) : names = names . split ( ',' ) names = listify ( names ) return [ str ( name ) . strip ( ) for name in names ] | Coerce a string or nested list of strings into a flat list of strings . |
5,416 | def normalize_serial_number ( sn , max_length = None , left_fill = '0' , right_fill = str ( ) , blank = str ( ) , valid_chars = ' -0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' , invalid_chars = None , strip_whitespace = True , join = False , na = rex . nones ) : r if max_length is None : max_length =... | r Make a string compatible with typical serial number requirements |
5,417 | def strip_HTML ( s ) : result = '' total = 0 for c in s : if c == '<' : total = 1 elif c == '>' : total = 0 result += ' ' elif total == 0 : result += c return result | Simple clumsy slow HTML tag stripper |
5,418 | 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! |
5,419 | def listify ( values , N = 1 , delim = None ) : ans = [ ] if values is None else values if hasattr ( ans , '__iter__' ) and not isinstance ( ans , basestring ) : ans = list ( ans ) else : if isinstance ( delim , basestring ) and isinstance ( ans , basestring ) : try : ans = ans . split ( delim ) except ( IndexError , V... | Return an N - length list with elements values extrapolating as necessary . |
5,420 | 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 . |
5,421 | def strip_keys ( d , nones = False , depth = 0 ) : r 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 : warning... | r Strip whitespace from all dictionary keys to the depth indicated |
5,422 | 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 |
5,423 | 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 |
5,424 | def truncate ( s , max_len = 20 , ellipsis = '...' ) : r 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 : tru... | r Return string at most max_len characters or sequence elments appended with the ellipsis characters |
5,425 | def slash_product ( string_or_seq , slash = '/' , space = ' ' ) : if not isinstance ( string_or_seq , basestring ) : if not any ( slash in s for s in string_or_seq ) : return list ( string_or_seq ) ans = [ ] for s in string_or_seq : ans += slash_product ( s ) return slash_product ( ans ) if slash not in string_or_seq :... | Return a list of all possible meanings of a phrase containing slashes |
5,426 | 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" , npi... | Create a header a new image |
5,427 | def word_tokenize ( text ) : for ( regexp , replacement ) in RULES1 : text = sub ( regexp , replacement , text ) text = " " + text + " " for ( regexp , replacement ) in RULES2 : text = sub ( regexp , replacement , text ) for regexp in CONTRACTIONS : text = sub ( regexp , r"\1 \2 " , text ) return text . split ( ) | Split string text into word tokens using the Penn Treebank rules |
5,428 | 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 ) if addition and addition . upper ( ) not in [ a . upper ( ) for a in retValue [ 'house... | get_postcodedata - fetch information for postcode . |
5,429 | def get_signalcheck ( self , sar , ** params ) : params = sar endpoint = 'rest/signal/check' retValue = self . _API__request ( endpoint , 'POST' , params = params , convJSON = True ) return retValue | get_signalcheck - perform a signal check . |
5,430 | 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' : reques... | request - Returns dict of response from postcode . nl API . |
5,431 | 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 )... | Fit a line to the x y data supplied and plot it along with teh raw samples |
5,432 | 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... | Scatter plot with colored markers depending on the discrete values in a category column |
5,433 | 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' ) Axes3D . scatter ( * [ df [ co... | 3 - D Point cloud for plotting things like mesh models of horses ; ) |
5,434 | def show ( self , block = False ) : try : plt . show ( block = block ) except ValueError : plt . show ( ) | Display the last image drawn |
5,435 | def save ( self , filename ) : plt . savefig ( filename , fig = self . fig , facecolor = 'black' , edgecolor = 'black' ) | save colormap to file |
5,436 | def getp ( self , name ) : name = self . _mapping . get ( name , name ) return self . params [ name ] | Get the named parameter . |
5,437 | 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 . war... | 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 . |
5,438 | 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 ] ret... | 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 fu... |
5,439 | 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 |
5,440 | def proj4_to_epsg ( projection ) : def make_definition ( value ) : return { x . strip ( ) . lower ( ) for x in value . split ( '+' ) if x } match = EPSG_RE . search ( projection . srs ) if match : return int ( match . group ( 1 ) ) pyproj_data_dir = os . path . join ( os . path . dirname ( pyproj . __file__ ) , 'data' ... | Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails |
5,441 | 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 |
5,442 | 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 |
5,443 | 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 . |
5,444 | def _load ( self , config ) : if isstring ( config ) : self . filename = config params = yaml . load ( open ( config ) ) elif isinstance ( config , Config ) : self . filename = config . filename params = copy . deepcopy ( config ) elif isinstance ( config , dict ) : params = copy . deepcopy ( config ) elif config is No... | Load this config from an existing config |
5,445 | def _validate ( self ) : 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_likelih... | Enforce some structure to the config file |
5,446 | 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' ] [ 'sea... | Join dirnames and filenames from config . |
5,447 | 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 )... | Write a copy of this config object . |
5,448 | 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 . |
5,449 | 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 . |
5,450 | 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 . |
5,451 | def index_pix_in_pixels ( pix , pixels , sort = False , outside = - 1 ) : if sort : pixels = np . sort ( pixels ) index = np . searchsorted ( pixels , pix ) if np . isscalar ( index ) : if not np . in1d ( pix , pixels ) . any ( ) : index = outside else : index [ ~ np . in1d ( pix , pixels ) ] = outside return index | Find the indices of a set of pixels into another set of pixels . !!! ASSUMES SORTED PIXELS !!! |
5,452 | 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 |
5,453 | 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' ) , ( 'va... | Mimic the healpy header keywords . |
5,454 | def write_partial_map ( filename , data , nside , coord = None , nest = False , header = None , dtype = None , ** kwargs ) : 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 = hea... | Partial HEALPix maps are used to efficiently store maps of the sky by only writing out the pixels that contain data . |
5,455 | 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 , file... | Merge header information from likelihood files . |
5,456 | 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 |
5,457 | 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 ... | Write the results output file |
5,458 | 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 , sr... | Write the membership output file |
5,459 | 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 fin... | Create plots of mcmc output |
5,460 | 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 . |
5,461 | 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 , repla... | Caches variants_dict and replace_dict in a single database hit . |
5,462 | 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 ) , ** er... | Translate a botocore . exceptions . ClientError into a dynamo3 error |
5,463 | 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 |
5,464 | def generate_lines ( text , ext = [ '.txt' , '.md' , '.rst' , '.asciidoc' , '.asc' ] ) : r 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 . fr... | r Yield text one line at a time from from a single file path files in a directory or a text string |
5,465 | def add ( self , now , num ) : if num == 0 : return self . points . append ( ( now , num ) ) | Add a timestamp and date to the data |
5,466 | 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 |
5,467 | 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 |
5,468 | def on_capacity ( self , connection , command , query_kwargs , response , capacity ) : now = time . time ( ) args = ( connection , command , query_kwargs , response , capacity ) self . _wait ( args , now , self . total_cap , self . _total_consumed , capacity . total ) if capacity . tablename in self . table_caps : tabl... | Hook that runs in response to a returned capacity event |
5,469 | 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... | Check the consumed capacity against the limit and sleep |
5,470 | 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 Va... | Send a case creation to SalesForces to create a ticket . |
5,471 | 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 . ... | Get the sum of spending for this category up to and including the given month . |
5,472 | def plot ( self , value = None , pixel = None ) : 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 ] = 1 map_roi [ self . pixels_annulus ] = 0 map_roi [ self . pixels_... | Plot the ROI |
5,473 | 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 . |
5,474 | def getCatalogPixels ( self ) : filenames = self . config . getFilenames ( ) nside_catalog = self . config . params [ 'coords' ] [ 'nside_catalog' ] nside_pixel = self . config . params [ 'coords' ] [ 'nside_pixel' ] superpix = ugali . utils . skymap . superpixel ( self . pixels , nside_pixel , nside_catalog ) superpix... | Return the catalog pixels spanned by this ROI . |
5,475 | 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 . inc... | Create the index schema |
5,476 | 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 |
5,477 | 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 |
5,478 | 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 |
5,479 | def from_response ( cls , response ) : hash_key = None range_key = None if 'KeySchema' in response : attrs = dict ( ( ( d [ 'AttributeName' ] , DynamoKey ( d [ 'AttributeName' ] , d [ 'AttributeType' ] ) ) for d in response [ 'AttributeDefinitions' ] ) ) hash_key = attrs [ response [ 'KeySchema' ] [ 0 ] [ 'AttributeNam... | Create a Table from returned Dynamo data |
5,480 | 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 |
5,481 | 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 . |
5,482 | 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 . |
5,483 | def subscribe ( self , message , handler ) : with self . _lock : ref = WeakCallable ( handler , self . _on_collect ) self . _subscribers [ message ] . append ( ref ) | Adds hander for specified message . |
5,484 | def unsubscribe ( self , message , handler ) : with self . _lock : self . _subscribers [ message ] . remove ( WeakCallable ( handler ) ) | Removes handler from message listeners . |
5,485 | 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 : pass | Event handler for timer that processes all queued messages . |
5,486 | def emit ( self , * args , ** kwargs ) : self . _messanger . send ( self , * args , ** kwargs ) | Emits this signal . As result all handlers will be invoked . |
5,487 | 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 . |
5,488 | 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 :... | Like os . walk but takes level kwarg that indicates how deep the recursion will go . |
5,489 | 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' ] =... | Use python builtin equivalents to unix stat command and return dict containing stat data about a file |
5,490 | def split ( config , dirname = 'split' , force = False ) : config = Config ( config ) filenames = config . getFilenames ( ) basedir , basename = os . path . split ( config [ 'mask' ] [ 'dirname' ] ) outdir = mkdir ( os . path . join ( basedir , dirname ) ) nside_catalog = config [ 'coords' ] [ 'nside_catalog' ] nside_p... | Take a pre - existing maglim map and divide it into chunks consistent with the catalog pixels . |
5,491 | 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... | Loop through pixels containing catalog objects and calculate the magnitude limit . This gets a bit convoluted due to all the different pixel resolutions ... |
5,492 | def get_variable_set ( self , variable_set , data ) : if data . get ( 'dynamic_layers' ) : variable_set = [ ] 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_... | Filters the given variable set based on request parameters |
5,493 | def apply_time_to_configurations ( self , configurations , data ) : time_value = None if data . get ( 'time' ) : time_value = data [ 'time' ] 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_v... | Applies the correct time index to configurations |
5,494 | 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' : 'pn... | Returns default values for the get image form |
5,495 | 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 [ 'si... | Render image interface |
5,496 | 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 |
5,497 | 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 : data = json [ 0 ] return Term ( name = data [ 'name' ] , title = dat... | Retrieve a specific term and condition . |
5,498 | 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 |
5,499 | 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_rat... | Returns this bbox normalized to match the ratio of the given size . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.