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,300 | def calc_signal_spatial ( self ) : # Calculate the surface intensity self . surface_intensity_sparse = self . calc_surface_intensity ( ) # Calculate the probability per object-by-object level self . surface_intensity_object = self . kernel . pdf ( self . catalog . lon , self . catalog . lat ) # Spatial component of sig... | Calculate the spatial signal probability for each catalog object . | 99 | 12 |
5,301 | def fit_richness ( self , atol = 1.e-3 , maxiter = 50 ) : # Check whether the signal probability for all objects are zero # This can occur for finite kernels on the edge of the survey footprint if np . isnan ( self . u ) . any ( ) : logger . warning ( "NaN signal probability found" ) return 0. , 0. , None if not np . a... | Maximize the log - likelihood as a function of richness . | 387 | 12 |
5,302 | def resolve_reference ( self , ref ) : url , resolved = self . resolver . resolve ( ref ) return resolved | Resolve a JSON Pointer object reference to the object itself . | 25 | 13 |
5,303 | def get_path ( self , path ) : mapping = self . get_path_mapping ( path ) return self . path_class ( api = self , path = path , mapping = mapping ) | Construct a Path object from a path string . | 42 | 9 |
5,304 | def from_file ( cls , filename ) : with open ( filename ) as infp : if filename . endswith ( '.yaml' ) or filename . endswith ( '.yml' ) : import yaml data = yaml . safe_load ( infp ) else : import json data = json . load ( infp ) return cls . from_data ( data ) | Construct an APIDefinition by parsing the given filename . | 83 | 12 |
5,305 | def _server_error_message ( url , message ) : msg = _error_message . format ( url = url , message = message ) log . error ( msg ) return msg | Log and return a server error message . | 38 | 8 |
5,306 | def make_request ( url , method = 'GET' , query = None , body = None , auth = None , timeout = 10 , client = None , macaroons = None ) : headers = { } kwargs = { 'timeout' : timeout , 'headers' : headers } # Handle the request body. if body is not None : if isinstance ( body , collections . Mapping ) : body = json . du... | Make a request with the provided data . | 484 | 8 |
5,307 | def get_plans ( self , reference ) : response = make_request ( '{}charm?charm-url={}' . format ( self . url , 'cs:' + reference . path ( ) ) , timeout = self . timeout , client = self . _client ) try : return tuple ( map ( lambda plan : Plan ( url = plan [ 'url' ] , plan = plan [ 'plan' ] , created_on = datetime . date... | Get the plans for a given charm . | 220 | 8 |
5,308 | def list_wallets ( self ) : response = make_request ( '{}wallet' . format ( self . url ) , timeout = self . timeout , client = self . _client ) try : total = response [ 'total' ] return { 'credit' : response [ 'credit' ] , 'total' : WalletTotal ( limit = total [ 'limit' ] , budgeted = total [ 'budgeted' ] , available =... | Get the list of wallets . | 287 | 6 |
5,309 | def get_wallet ( self , wallet_name ) : response = make_request ( '{}wallet/{}' . format ( self . url , wallet_name ) , timeout = self . timeout , client = self . _client ) try : total = response [ 'total' ] return { 'credit' : response [ 'credit' ] , 'limit' : response [ 'limit' ] , 'total' : WalletTotal ( limit = tot... | Get a single wallet . | 206 | 5 |
5,310 | def update_wallet ( self , wallet_name , limit ) : request = { 'update' : { 'limit' : str ( limit ) , } } return make_request ( '{}wallet/{}' . format ( self . url , wallet_name ) , method = 'PATCH' , body = request , timeout = self . timeout , client = self . _client ) | Update a wallet with a new limit . | 82 | 8 |
5,311 | def delete_wallet ( self , wallet_name ) : return make_request ( '{}wallet/{}' . format ( self . url , wallet_name ) , method = 'DELETE' , timeout = self . timeout , client = self . _client ) | Delete a wallet . | 58 | 4 |
5,312 | def create_budget ( self , wallet_name , model_uuid , limit ) : request = { 'model' : model_uuid , 'limit' : limit , } return make_request ( '{}wallet/{}/budget' . format ( self . url , wallet_name ) , method = 'POST' , body = request , timeout = self . timeout , client = self . _client ) | Create a new budget for a model and wallet . | 88 | 10 |
5,313 | def delete_budget ( self , model_uuid ) : return make_request ( '{}model/{}/budget' . format ( self . url , model_uuid ) , method = 'DELETE' , timeout = self . timeout , client = self . _client ) | Delete a budget . | 62 | 4 |
5,314 | def confusion ( df , labels = [ 'neg' , 'pos' ] ) : c = pd . DataFrame ( np . zeros ( ( 2 , 2 ) ) , dtype = int ) a , b = df . columns [ : 2 ] # labels[df.columns[:2]] c . columns = sorted ( set ( df [ a ] ) ) [ : 2 ] c . columns . name = a c . index = list ( c . columns ) c . index . name = b c1 , c2 = c . columns c [... | Binary classification confusion | 258 | 4 |
5,315 | def thresh_from_spec ( spec , labels , scores , * * kwargs ) : cost_fun . verbose = kwargs . pop ( 'verbose' , cost_fun . verbose ) cost_fun . target = spec return minimize ( cost_fun , x0 = [ .5 ] , args = ( labels , scores ) , method = 'SLSQP' , constraints = ( { 'type' : 'ineq' , 'fun' : lambda x : np . array ( [ x ... | r Find the threshold level that accomplishes the desired specificity | 143 | 11 |
5,316 | def add_dicts ( d1 , d2 ) : if d1 is None : return d2 if d2 is None : return d1 keys = set ( d1 ) keys . update ( set ( d2 ) ) ret = { } for key in keys : v1 = d1 . get ( key ) v2 = d2 . get ( key ) if v1 is None : ret [ key ] = v2 elif v2 is None : ret [ key ] = v1 else : ret [ key ] = v1 + v2 return ret | Merge two dicts of addable values | 118 | 9 |
5,317 | def _update_capacity ( self , data ) : if 'ConsumedCapacity' in data : # This is all for backwards compatibility consumed = data [ 'ConsumedCapacity' ] if not isinstance ( consumed , list ) : consumed = [ consumed ] for cap in consumed : self . capacity += cap . get ( 'CapacityUnits' , 0 ) self . table_capacity += cap ... | Update the consumed capacity metrics | 237 | 5 |
5,318 | def fetch ( self ) : self . limit . set_request_args ( self . kwargs ) data = self . connection . call ( * self . args , * * self . kwargs ) self . limit . post_fetch ( data ) self . last_evaluated_key = data . get ( 'LastEvaluatedKey' ) if self . last_evaluated_key is None : self . kwargs . pop ( 'ExclusiveStartKey' ,... | Fetch more results from Dynamo | 203 | 6 |
5,319 | def build_kwargs ( self ) : keys , self . keys = self . keys [ : MAX_GET_BATCH ] , self . keys [ MAX_GET_BATCH : ] query = { 'ConsistentRead' : self . consistent } if self . attributes is not None : query [ 'ProjectionExpression' ] = self . attributes if self . alias : query [ 'ExpressionAttributeNames' ] = self . alia... | Construct the kwargs to pass to batch_get_item | 133 | 13 |
5,320 | def fetch ( self ) : kwargs = self . build_kwargs ( ) data = self . connection . call ( 'batch_get_item' , * * kwargs ) if 'UnprocessedKeys' in data : for items in six . itervalues ( data [ 'UnprocessedKeys' ] ) : self . keys . extend ( items [ 'Keys' ] ) # Getting UnprocessedKeys indicates that we are exceeding our # ... | Fetch a set of items from their keys | 230 | 9 |
5,321 | def copy ( self ) : return Limit ( self . scan_limit , self . item_limit , self . min_scan_limit , self . strict , self . filter ) | Return a copy of the limit | 37 | 6 |
5,322 | def set_request_args ( self , args ) : if self . scan_limit is not None : args [ 'Limit' ] = self . scan_limit elif self . item_limit is not None : args [ 'Limit' ] = max ( self . item_limit , self . min_scan_limit ) else : args . pop ( 'Limit' , None ) | Set the Limit parameter into the request args | 80 | 8 |
5,323 | def complete ( self ) : if self . scan_limit is not None and self . scan_limit == 0 : return True if self . item_limit is not None and self . item_limit == 0 : return True return False | Return True if the limit has been reached | 48 | 8 |
5,324 | def accept ( self , item ) : accept = self . filter ( item ) if accept and self . item_limit is not None : if self . item_limit > 0 : self . item_limit -= 1 elif self . strict : return False return accept | Apply the filter and item_limit and return True to accept | 54 | 12 |
5,325 | def returned ( n ) : ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk ( ) >> drop ( 1 ) >> takei ( xrange ( n - 1 ) ) : if pos == Origin : return True return False | Generate a random walk and return True if the walker has returned to the origin after taking n steps . | 63 | 22 |
5,326 | def first_return ( ) : walk = randwalk ( ) >> drop ( 1 ) >> takewhile ( lambda v : v != Origin ) >> list return len ( walk ) | Generate a random walk and return its length upto the moment that the walker first returns to the origin . | 36 | 23 |
5,327 | def seq ( start = 0 , step = 1 ) : def seq ( a , d ) : while 1 : yield a a += d return seq ( start , step ) | An arithmetic sequence generator . Works with any type with + defined . | 35 | 13 |
5,328 | def pipe ( inpipe , outpipe ) : if hasattr ( outpipe , '__pipe__' ) : return outpipe . __pipe__ ( inpipe ) elif hasattr ( outpipe , '__call__' ) : return outpipe ( inpipe ) else : raise BrokenPipe ( 'No connection mechanism defined' ) | Connect inpipe and outpipe . If outpipe is not a Stream instance it should be an function callable on an iterable . | 71 | 27 |
5,329 | def submit ( self , * items ) : with self . lock : if self . closed : raise BrokenPipe ( 'Job submission has been closed.' ) id = self . jobcount self . _status += [ 'SUBMITTED' ] * len ( items ) self . jobcount += len ( items ) for item in items : self . waitqueue . put ( ( id , item ) ) id += 1 if len ( items ) == 1 ... | Return job ids assigned to the submitted items . | 113 | 10 |
5,330 | def cancel ( self , * ids ) : ncancelled = 0 with self . lock : for id in ids : try : if self . _status [ id ] == 'SUBMITTED' : self . _status [ id ] = 'CANCELLED' ncancelled += 1 except IndexError : pass return ncancelled | Try to cancel jobs with associated ids . Return the actual number of jobs cancelled . | 76 | 17 |
5,331 | def shutdown ( self ) : with self . lock : self . pool . inqueue . put ( StopIteration ) # Stop the pool workers self . waitqueue . put ( StopIteration ) # Stop the input_feeder _iterqueue ( self . waitqueue ) >> item [ - 1 ] # Exhaust the waitqueue self . closed = True self . join ( ) | Shut down the Executor . Suspend all waiting jobs . Running workers will terminate after finishing their current job items . The call will block until all workers are terminated . | 78 | 33 |
5,332 | def main ( ) : arguments = docopt ( __doc__ , version = __version__ ) if arguments [ 'configure' ] and flag : configure ( ) if arguments [ 'cuisine' ] : if arguments [ 'list' ] : cuisine ( 'list' ) else : cuisine ( arguments [ '<cuisine-id>' ] ) elif arguments [ 'surprise' ] : surprise ( ) elif arguments [ 'reviews' ] ... | monica helps you order food from the timeline | 206 | 9 |
5,333 | def _get_requirements ( fname ) : packages = _read ( fname ) . split ( '\n' ) packages = ( p . strip ( ) for p in packages ) packages = ( p for p in packages if p and not p . startswith ( '#' ) ) return list ( packages ) | Create a list of requirements from the output of the pip freeze command saved in a text file . | 68 | 19 |
5,334 | def TermsProcessor ( instance , placeholder , rendered_content , original_context ) : if 'terms' in original_context : return rendered_content return mark_safe ( replace_terms ( rendered_content ) ) | Adds links all placeholders plugins except django - terms plugins | 45 | 12 |
5,335 | def time_stops ( self ) : if not self . supports_time : return [ ] if self . service . calendar == 'standard' : units = self . service . time_interval_units interval = self . service . time_interval steps = [ self . time_start ] if units in ( 'years' , 'decades' , 'centuries' ) : if units == 'years' : years = interval ... | Valid time steps for this service as a list of datetime objects . | 427 | 14 |
5,336 | def _parse_coords ( self , opts ) : # The coordinates are mutually exclusive, so # shouldn't have to worry about over-writing them. if 'coords' in vars ( opts ) : return radius = vars ( opts ) . get ( 'radius' , 0 ) gal = None if vars ( opts ) . get ( 'gal' ) is not None : gal = opts . gal elif vars ( opts ) . get ( 'c... | Parse target coordinates in various ways ... | 306 | 8 |
5,337 | def default_value ( self ) : if callable ( self . default ) and self . call_default : return self . default ( ) return self . default | Property to return the default value . | 33 | 7 |
5,338 | def raw_value ( self ) : if self . parent_setting is not None : return self . parent_setting . raw_value [ self . full_name ] else : return getattr ( settings , self . full_name ) | Property to return the variable defined in django . conf . settings . | 49 | 14 |
5,339 | def get_value ( self ) : try : value = self . raw_value except ( AttributeError , KeyError ) as err : self . _reraise_if_required ( err ) default_value = self . default_value if self . transform_default : return self . transform ( default_value ) return default_value else : return self . transform ( value ) | Return the transformed raw or default value . | 79 | 8 |
5,340 | def run_validators ( self , value ) : errors = [ ] for validator in self . validators : try : validator ( value ) except ValidationError as error : errors . extend ( error . messages ) if errors : raise ValidationError ( errors ) | Run the validators on the setting value . | 56 | 9 |
5,341 | def transform ( self , path ) : if path is None or not path : return None obj_parent_modules = path . split ( "." ) objects = [ obj_parent_modules . pop ( - 1 ) ] while True : try : parent_module_path = "." . join ( obj_parent_modules ) parent_module = importlib . import_module ( parent_module_path ) break except Impor... | Transform a path into an actual Python object . | 171 | 9 |
5,342 | def get_value ( self ) : try : self . raw_value except ( AttributeError , KeyError ) as err : self . _reraise_if_required ( err ) default_value = self . default_value if self . transform_default : return self . transform ( default_value ) return default_value else : # If setting is defined, load values of all subsettin... | Return dictionary with values of subsettings . | 116 | 8 |
5,343 | def sum_mags ( mags , weights = None ) : flux = 10 ** ( - np . asarray ( mags ) / 2.5 ) if weights is None : return - 2.5 * np . log10 ( np . sum ( flux ) ) else : return - 2.5 * np . log10 ( np . sum ( weights * flux ) ) | Sum an array of magnitudes in flux space . | 78 | 10 |
5,344 | def absolute_magnitude ( distance_modulus , g , r , prob = None ) : V = g - 0.487 * ( g - r ) - 0.0249 flux = np . sum ( 10 ** ( - ( V - distance_modulus ) / 2.5 ) ) Mv = - 2.5 * np . log10 ( flux ) return Mv | Calculate the absolute magnitude from a set of bands | 81 | 11 |
5,345 | def observableFractionCDF ( self , mask , distance_modulus , mass_min = 0.1 ) : method = 'step' mass_init , mass_pdf , mass_act , mag_1 , mag_2 = self . sample ( mass_min = mass_min , full_data_range = False ) mag_1 = mag_1 + distance_modulus mag_2 = mag_2 + distance_modulus mask_1 , mask_2 = mask . mask_roi_unique . T... | Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask . Incorporates simplistic photometric errors . | 600 | 32 |
5,346 | def histogram2d ( self , distance_modulus = None , delta_mag = 0.03 , steps = 10000 ) : if distance_modulus is not None : self . distance_modulus = distance_modulus # Isochrone will be binned, so might as well sample lots of points mass_init , mass_pdf , mass_act , mag_1 , mag_2 = self . sample ( mass_steps = steps ) #... | Return a 2D histogram the isochrone in mag - mag space . | 408 | 16 |
5,347 | def pdf_mmd ( self , lon , lat , mag_1 , mag_2 , distance_modulus , mask , delta_mag = 0.03 , steps = 1000 ) : logger . info ( 'Running MMD pdf' ) roi = mask . roi mmd = self . signalMMD ( mask , distance_modulus , delta_mag = delta_mag , mass_steps = steps ) # This is fragile, store this information somewhere else... ... | Ok now here comes the beauty of having the signal MMD . | 398 | 13 |
5,348 | def raw_separation ( self , mag_1 , mag_2 , steps = 10000 ) : # http://stackoverflow.com/q/12653120/ mag_1 = np . array ( mag_1 , copy = False , ndmin = 1 ) mag_2 = np . array ( mag_2 , copy = False , ndmin = 1 ) init , pdf , act , iso_mag_1 , iso_mag_2 = self . sample ( mass_steps = steps ) iso_mag_1 += self . distanc... | Calculate the separation in magnitude - magnitude space between points and isochrone . Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point . | 312 | 39 |
5,349 | def separation ( self , mag_1 , mag_2 ) : iso_mag_1 = self . mag_1 + self . distance_modulus iso_mag_2 = self . mag_2 + self . distance_modulus def interp_iso ( iso_mag_1 , iso_mag_2 , mag_1 , mag_2 ) : interp_1 = scipy . interpolate . interp1d ( iso_mag_1 , iso_mag_2 , bounds_error = False ) interp_2 = scipy . interpo... | Calculate the separation between a specific point and the isochrone in magnitude - magnitude space . Uses an interpolation | 557 | 24 |
5,350 | def get_handler ( self , operation_id ) : handler = ( self . handlers . get ( operation_id ) or self . handlers . get ( snake_case ( operation_id ) ) ) if handler : return handler raise MissingHandler ( 'Missing handler for operation %s (tried %s too)' % ( operation_id , snake_case ( operation_id ) ) ) | Get the handler function for a given operation . | 81 | 9 |
5,351 | def add_handlers ( self , namespace ) : if isinstance ( namespace , str ) : namespace = import_module ( namespace ) if isinstance ( namespace , dict ) : namespace = namespace . items ( ) else : namespace = vars ( namespace ) . items ( ) for name , value in namespace : if name . startswith ( '_' ) : continue if isfuncti... | Add handler functions from the given namespace for instance a module . | 98 | 12 |
5,352 | def get_context ( self , arr , expr , context ) : expression_names = [ x for x in self . get_expression_names ( expr ) if x not in set ( context . keys ( ) ) . union ( [ 'i' ] ) ] if len ( expression_names ) != 1 : raise ValueError ( 'The expression must have exactly one variable.' ) return { expression_names [ 0 ] : a... | Returns a context dictionary for use in evaluating the expression . | 90 | 11 |
5,353 | def execute ( self , array_in , expression , * * kwargs ) : context = self . get_context ( array_in , expression , kwargs ) context . update ( kwargs ) return ma . masked_where ( self . evaluate_expression ( expression , context ) , array_in ) | Creates and returns a masked view of the input array . | 66 | 12 |
5,354 | def timeout_error ( url , timeout ) : msg = 'Request timed out: {} timeout: {}s' . format ( url , timeout ) log . warning ( msg ) return ServerError ( msg ) | Raise a server error indicating a request timeout to the given URL . | 42 | 14 |
5,355 | def histogram ( title , title_x , title_y , x , bins_x ) : plt . figure ( ) plt . hist ( x , bins_x ) plt . xlabel ( title_x ) plt . ylabel ( title_y ) plt . title ( title ) | Plot a basic histogram . | 65 | 6 |
5,356 | def twoDimensionalHistogram ( title , title_x , title_y , z , bins_x , bins_y , lim_x = None , lim_y = None , vmin = None , vmax = None ) : plt . figure ( ) mesh_x , mesh_y = np . meshgrid ( bins_x , bins_y ) if vmin != None and vmin == vmax : plt . pcolor ( mesh_x , mesh_y , z ) else : plt . pcolor ( mesh_x , mesh_y ,... | Create a two - dimension histogram plot or binned map . | 219 | 13 |
5,357 | def twoDimensionalScatter ( title , title_x , title_y , x , y , lim_x = None , lim_y = None , color = 'b' , size = 20 , alpha = None ) : plt . figure ( ) plt . scatter ( x , y , c = color , s = size , alpha = alpha , edgecolors = 'none' ) plt . xlabel ( title_x ) plt . ylabel ( title_y ) plt . title ( title ) if type (... | Create a two - dimensional scatter plot . | 176 | 8 |
5,358 | def drawHealpixMap ( hpxmap , lon , lat , size = 1.0 , xsize = 501 , coord = 'GC' , * * kwargs ) : ax = plt . gca ( ) x = np . linspace ( - size , size , xsize ) y = np . linspace ( - size , size , xsize ) xx , yy = np . meshgrid ( x , y ) coord = coord . upper ( ) if coord == 'GC' : #Assumes map and (lon,lat) are Gala... | Draw local projection of healpix map . | 410 | 9 |
5,359 | def getDSSImage ( ra , dec , radius = 1.0 , xsize = 800 , * * kwargs ) : import subprocess import tempfile service = 'skyview' if service == 'stsci' : url = "https://archive.stsci.edu/cgi-bin/dss_search?" scale = 2.0 * radius * 60. params = dict ( ra = '%.3f' % ra , dec = '%.3f' % dec , width = scale , height = scale ,... | Download Digitized Sky Survey images | 376 | 6 |
5,360 | def draw_slices ( hist , func = np . sum , * * kwargs ) : from mpl_toolkits . axes_grid1 import make_axes_locatable kwargs . setdefault ( 'ls' , '-' ) ax = plt . gca ( ) data = hist # Slices vslice = func ( data , axis = 0 ) hslice = func ( data , axis = 1 ) npix = np . array ( data . shape ) #xlim,ylim = plt.array(zip... | Draw horizontal and vertical slices through histogram | 604 | 8 |
5,361 | def plotSkymapCatalog ( lon , lat , * * kwargs ) : fig = plt . figure ( ) ax = plt . subplot ( 111 , projection = projection ) drawSkymapCatalog ( ax , lon , lat , * * kwargs ) | Plot a catalog of coordinates on a full - sky map . | 58 | 12 |
5,362 | def makePath ( x_path , y_path , epsilon = 1.e-10 ) : x_path_closed = np . concatenate ( [ x_path , x_path [ : : - 1 ] ] ) y_path_closed = np . concatenate ( [ y_path , epsilon + y_path [ : : - 1 ] ] ) path = matplotlib . path . Path ( list ( zip ( x_path_closed , y_path_closed ) ) ) return path | Create closed path . | 113 | 4 |
5,363 | def drawMask ( self , ax = None , mask = None , mtype = 'maglim' ) : if not ax : ax = plt . gca ( ) if mask is None : mask = ugali . analysis . loglike . createMask ( self . config , roi = self . roi ) mask_map = hp . UNSEEN * np . ones ( hp . nside2npix ( self . nside ) ) if mtype . lower ( ) == 'maglim' : mask_map [ ... | Draw the maglim from the mask . | 347 | 8 |
5,364 | def parse ( self , configManager , config ) : parser = ConfigParser . RawConfigParser ( ) configOptions = dict ( ) configFile = self . _getConfigFile ( config ) if configFile : parser . readfp ( configFile ) for section in parser . sections ( ) : if self . sections is None or section in self . sections : configOptions ... | Parse configuration options out of an . ini configuration file . | 88 | 13 |
5,365 | def write_chapter ( self ) : self . paragraphs = [ ] self . paragraphs . append ( '\n' ) for x in range ( randint ( 0 , 50 ) ) : p = Paragraph ( self . model ) self . paragraphs . append ( p . get_paragraph ( ) ) self . paragraphs . append ( '\n' ) return self . paragraphs | Create a chapter that contains a random number of paragraphs | 77 | 10 |
5,366 | def buildcss ( app , buildpath , imagefile ) : # set default values div = 'body' repeat = 'repeat-y' position = 'center' attachment = 'scroll' if app . config . sphinxmark_div != 'default' : div = app . config . sphinxmark_div if app . config . sphinxmark_repeat is False : repeat = 'no-repeat' if app . config . sphinxm... | Create CSS file . | 260 | 4 |
5,367 | def createimage ( app , srcdir , buildpath ) : text = app . config . sphinxmark_text # draw transparent background width = app . config . sphinxmark_text_width height = app . config . sphinxmark_text_spacing img = Image . new ( 'RGBA' , ( width , height ) , ( 255 , 255 , 255 , 0 ) ) d = ImageDraw . Draw ( img ) # set f... | Create PNG image from string . | 375 | 6 |
5,368 | def getimage ( app ) : # append source directory to TEMPLATE_PATH so template is found srcdir = os . path . abspath ( os . path . dirname ( __file__ ) ) TEMPLATE_PATH . append ( srcdir ) staticbase = '_static' buildpath = os . path . join ( app . outdir , staticbase ) try : os . makedirs ( buildpath ) except OSError : ... | Get image file . | 415 | 4 |
5,369 | def watermark ( app , env ) : if app . config . sphinxmark_enable is True : LOG . info ( 'adding watermark...' , nonl = True ) buildpath , imagefile = getimage ( app ) cssname = buildcss ( app , buildpath , imagefile ) app . add_css_file ( cssname ) LOG . info ( ' done' ) | Add watermark . | 85 | 4 |
5,370 | def setup ( app ) : app . add_config_value ( 'sphinxmark_enable' , False , 'html' ) app . add_config_value ( 'sphinxmark_div' , 'default' , 'html' ) app . add_config_value ( 'sphinxmark_border' , None , 'html' ) app . add_config_value ( 'sphinxmark_repeat' , True , 'html' ) app . add_config_value ( 'sphinxmark_fixed' ,... | Configure setup for Sphinx extension . | 382 | 8 |
5,371 | def gammalnStirling ( z ) : return ( 0.5 * ( np . log ( 2. * np . pi ) - np . log ( z ) ) ) + ( z * ( np . log ( z + ( 1. / ( ( 12. * z ) - ( 1. / ( 10. * z ) ) ) ) ) - 1. ) ) | Uses Stirling s approximation for the log - gamma function suitable for large arguments . | 80 | 17 |
5,372 | def satellite ( isochrone , kernel , stellar_mass , distance_modulus , * * kwargs ) : mag_1 , mag_2 = isochrone . simulate ( stellar_mass , distance_modulus ) lon , lat = kernel . simulate ( len ( mag_1 ) ) return mag_1 , mag_2 , lon , lat | Wrapping the isochrone and kernel simulate functions . | 77 | 11 |
5,373 | def detectability ( self , * * kwargs ) : distance_modulus = kwargs . get ( 'distance_modulus' ) distance = mod2dist ( distance_modulus ) stellar_mass = kwargs . get ( 'stellar_mass' ) extension = kwargs . get ( 'extension' ) # Normalized to 10^3 Msolar at mod=18 norm = 10 ** 3 / mod2dist ( 18 ) ** 2 detect = stellar_m... | An a priori detectability proxy . | 111 | 8 |
5,374 | def _create_catalog ( self , catalog = None ) : if catalog is None : catalog = ugali . analysis . loglike . createCatalog ( self . config , self . roi ) cut = self . mask . restrictCatalogToObservableSpace ( catalog ) self . catalog = catalog . applyCut ( cut ) | Bundle it . | 69 | 4 |
5,375 | def _setup_subpix ( self , nside = 2 ** 16 ) : # Only setup once... if hasattr ( self , 'subpix' ) : return # Simulate over full ROI self . roi_radius = self . config [ 'coords' ] [ 'roi_radius' ] # Setup background spatial stuff logger . info ( "Setup subpixels..." ) self . nside_pixel = self . config [ 'coords' ] [ '... | Subpixels for random position generation . | 271 | 8 |
5,376 | def _setup_cmd ( self , mode = 'cloud-in-cells' ) : # Only setup once... if hasattr ( self , 'bkg_lambda' ) : return logger . info ( "Setup color..." ) # In the limit theta->0: 2*pi*(1-cos(theta)) -> pi*theta**2 # (Remember to convert from sr to deg^2) #solid_angle_roi = sr2deg(2*np.pi*(1-np.cos(np.radians(self.roi_rad... | The purpose here is to create a more finely binned background CMD to sample from . | 392 | 18 |
5,377 | def toy_background ( self , mc_source_id = 2 , seed = None ) : logger . info ( "Running toy background simulation..." ) size = 20000 nstar = np . random . poisson ( size ) #np.random.seed(0) logger . info ( "Simulating %i background stars..." % nstar ) ### # Random points from roi pixels ### idx = np.random.randint(len... | Quick uniform background generation . | 759 | 5 |
5,378 | def satellite ( self , stellar_mass , distance_modulus , mc_source_id = 1 , seed = None , * * kwargs ) : if seed is not None : np . random . seed ( seed ) isochrone = kwargs . pop ( 'isochrone' , self . isochrone ) kernel = kwargs . pop ( 'kernel' , self . kernel ) for k , v in kwargs . items ( ) : if k in kernel . par... | Create a simulated satellite . Returns a catalog object . | 832 | 10 |
5,379 | def makeHDU ( self , mag_1 , mag_err_1 , mag_2 , mag_err_2 , lon , lat , mc_source_id ) : if self . config [ 'catalog' ] [ 'coordsys' ] . lower ( ) == 'cel' and self . config [ 'coords' ] [ 'coordsys' ] . lower ( ) == 'gal' : lon , lat = ugali . utils . projector . gal2cel ( lon , lat ) elif self . config [ 'catalog' ]... | Create a catalog fits file object based on input data . | 531 | 11 |
5,380 | def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) ) | Return a dict with swapped keys and values | 38 | 8 |
5,381 | def inverted_dict_of_lists ( d ) : new_dict = { } for ( old_key , old_value_list ) in viewitems ( dict ( d ) ) : for new_key in listify ( old_value_list ) : new_dict [ new_key ] = old_key return new_dict | Return a dict where the keys are all the values listed in the values of the original dict | 71 | 18 |
5,382 | 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 | 303 | 15 |
5,383 | def clean_field_dict ( field_dict , cleaner = str . strip , time_zone = None ) : 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 | 132 | 20 |
5,384 | 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 | 78 | 14 |
5,385 | 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 . | 49 | 18 |
5,386 | 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 | 98 | 19 |
5,387 | def joined_seq ( seq , sep = None ) : 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 | 54 | 13 |
5,388 | 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 . | 163 | 15 |
5,389 | 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 | 156 | 11 |
5,390 | 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 | 428 | 18 |
5,391 | 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 ) ... | Similar to fuzzy_get but allows non - string keys and a list of possible keys | 212 | 17 |
5,392 | def update_file_ext ( filename , ext = 'txt' , sep = '.' ) : 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 | 91 | 13 |
5,393 | 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 | 111 | 5 |
5,394 | 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 | 80 | 9 |
5,395 | 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 | 106 | 20 |
5,396 | def make_float ( s , default = '' , ignore_commas = True ) : 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_sc... | r Coerce a string into a float | 129 | 9 |
5,397 | 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 . | 51 | 17 |
5,398 | 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 ) : # All 9 kwargs have persistent default... | r Make a string compatible with typical serial number requirements | 724 | 10 |
5,399 | 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 | 55 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.