signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def run_preassembly ( ) : """Run preassembly on a list of INDRA Statements ."""
if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) scorer = body . get ( 'scorer' ) return_toplevel = body . get ( 'return_toplevel' ) if scorer == 'w...
def get_first_host_port ( self ) : """Get the first mapping of the first ( lowest ) container port that has a mapping . Useful when a container publishes only one port . Note that unlike the Docker API , which sorts ports lexicographically ( e . g . ` ` 90 / tcp ` ` > ` ` 8000 / tcp ` ` ) , we sort ports nume...
mapped_ports = { p : m for p , m in self . ports . items ( ) if m is not None } if not mapped_ports : raise RuntimeError ( 'Container has no published ports' ) def sort_key ( port_string ) : port , proto = port_string . split ( '/' , 1 ) return int ( port ) , proto firt_port_spec = sorted ( mapped_ports . k...
def get_content_type ( content_type ) : """Extract the MIME type value from a content type string . Removes any subtype and parameter values that may be present in the string . Args : content _ type : str String with content type and optional subtype and parameter fields . Returns : str : String with on...
m = email . message . Message ( ) m [ 'Content-Type' ] = content_type return m . get_content_type ( )
def atlas_zonefile_find_push_peers ( zonefile_hash , peer_table = None , zonefile_bits = None , con = None , path = None ) : """Find the set of peers that do * not * have this zonefile ."""
if zonefile_bits is None : zonefile_bits = atlasdb_get_zonefile_bits ( zonefile_hash , path = path , con = con ) if len ( zonefile_bits ) == 0 : # we don ' t even know about it return [ ] push_peers = [ ] with AtlasPeerTableLocked ( peer_table ) as ptbl : for peer_hostport in ptbl . keys ( ) : ...
def check_ups_estimated_minutes_remaining ( the_session , the_helper , the_snmp_value ) : """OID . 1.3.6.1.2.1.33.1.2.3.0 MIB excerpt An estimate of the time to battery charge depletion under the present load conditions if the utility power is off and remains off , or if it were to be lost and remain off ...
the_helper . add_metric ( label = the_helper . options . type , value = the_snmp_value , uom = "minutes" ) the_helper . set_summary ( "Remaining runtime on battery is {} minutes" . format ( the_snmp_value ) )
def ordered_deduplicate ( sequence ) : """Returns the sequence as a tuple with the duplicates removed , preserving input order . Any duplicates following the first occurrence are removed . > > > ordered _ deduplicate ( [ 1 , 2 , 3 , 1 , 32 , 1 , 2 ] ) (1 , 2 , 3 , 32) Based on recipe from this StackOverfl...
seen = set ( ) # Micro optimization : each call to seen _ add saves an extra attribute # lookup in most iterations of the loop . seen_add = seen . add return tuple ( x for x in sequence if not ( x in seen or seen_add ( x ) ) )
def get_config_input_with_defaults ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_config = ET . Element ( "get_config" ) config = get_config input = ET . SubElement ( get_config , "input" ) with_defaults = ET . SubElement ( input , "with-defaults" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults" ) with_defaults . text = kwargs . pop ( 'with_de...
def encode_data_frame ( name , df , run ) : """Encode a Pandas DataFrame into the JSON / backend format . Writes the data to a file and returns a dictionary that we use to represent it in ` Summary ` ' s . Arguments : name ( str ) : Name of the DataFrame , eg . the summary key in which it ' s stored . Thi...
pandas = get_module ( "pandas" ) fastparquet = get_module ( "fastparquet" ) if not pandas or not fastparquet : raise wandb . Error ( "Failed to save data frame: unable to import either pandas or fastparquet." ) data_frame_id = generate_id ( ) # We have to call this wandb _ run _ id because that name is treated spec...
def tearpage_backend ( filename , teared_pages = None ) : """Copy filename to a tempfile , write pages to filename except the teared one . . . note : : Adapted from sciunto ' s code , https : / / github . com / sciunto / tear - pages : param filename : PDF filepath : param teared _ pages : Numbers of the pa...
# Handle default argument if teared_pages is None : teared_pages = [ 0 ] # Copy the pdf to a tmp file with tempfile . NamedTemporaryFile ( ) as tmp : # Copy the input file to tmp shutil . copy ( filename , tmp . name ) # Read the copied pdf # TODO : Use with syntax try : input_file = PdfFile...
def trace ( trace_obj ) : """Print recursive trace of given network protocol object : param trace _ obj : either a message , segement , or kind object"""
if pyhdb . tracing : t = TraceLogger ( ) tr = t . trace ( trace_obj ) print ( tr ) return tr
def _geoville_index_by_percentile ( self , data , percentile ) : """Calculate percentile of numpy stack and return the index of the chosen pixel ."""
# no _ obs = bn . allnan ( arr _ tmp [ " data " ] , axis = 0) data_tmp = np . array ( data , copy = True ) valid_obs = np . sum ( np . isfinite ( data_tmp ) , axis = 0 ) # replace NaN with maximum max_val = np . nanmax ( data_tmp ) + 1 data_tmp [ np . isnan ( data_tmp ) ] = max_val # sort - former NaNs will move to the...
def generate_sample_tf_module ( env_root , module_dir = None ) : """Generate skeleton Terraform sample module ."""
if module_dir is None : module_dir = os . path . join ( env_root , 'sampleapp.tf' ) generate_sample_module ( module_dir ) for i in [ 'backend-us-east-1.tfvars' , 'dev-us-east-1.tfvars' , 'main.tf' ] : shutil . copyfile ( os . path . join ( ROOT , 'templates' , 'terraform' , i ) , os . path . join ( module_dir ,...
def onKeyInCommandEntry ( self , event ) : '''Called when a key is pressed when the command entry box has focus .'''
if event . char == '\r' : self . onSendCommand ( ) self . canvas . focus_set ( )
def cublasSsbmv ( handle , uplo , n , k , alpha , A , lda , x , incx , beta , y , incy ) : """Matrix - vector product for real symmetric - banded matrix ."""
status = _libcublas . cublasSsbmv_v2 ( handle , _CUBLAS_FILL_MODE [ uplo ] , n , k , ctypes . byref ( ctypes . c_float ( alpha ) ) , int ( A ) , lda , int ( x ) , incx , ctypes . byref ( ctypes . c_float ( beta ) ) , int ( y ) , incy ) cublasCheckStatus ( status )
def _apply_filters_to_first_location_occurrence ( match_traversal , location_to_filters , already_filtered_locations ) : """Apply all filters for a specific location into its first occurrence in a given traversal . For each location in the given match traversal , construct a conjunction of all filters applied t...
new_match_traversal = [ ] newly_filtered_locations = set ( ) for match_step in match_traversal : # Apply all filters for a location to the first occurence of that location current_location = match_step . as_block . location if current_location in newly_filtered_locations : raise AssertionError ( u'The s...
def _storage_attach ( self , params ) : """Change storage medium in this VM . : param params : params to use with sub - command storageattach"""
args = shlex . split ( params ) yield from self . manager . execute ( "storageattach" , [ self . _vmname ] + args )
def relative_startup_config_file ( self ) : """Returns the startup - config file relative to the project directory . It ' s compatible with pre 1.3 projects . : returns : path to startup - config file . None if the file doesn ' t exist"""
path = os . path . join ( self . working_dir , 'startup-config.cfg' ) if os . path . exists ( path ) : return 'startup-config.cfg' else : return None
def collapse ( self ) : """Collapse into a StridedInterval instance . : return : A new StridedInterval instance ."""
if self . cardinality : r = None for si in self . _si_set : r = r . _union ( si ) if r is not None else si return r else : # This is an empty StridedInterval . . . return StridedInterval . empty ( self . _bits )
def login_redirect ( redirect = None , user = None ) : """Redirect user after successful sign in . First looks for a ` ` requested _ redirect ` ` . If not supplied will fall - back to the user specific account page . If all fails , will fall - back to the standard Django ` ` LOGIN _ REDIRECT _ URL ` ` setting...
if redirect : return redirect elif user is not None : return defaults . ACCOUNTS_LOGIN_REDIRECT_URL % { 'username' : user . username } else : return settings . LOGIN_REDIRECT_URL
def post ( self , endpoint , data , files = None , headers = None ) : # pylint : disable = unused - argument """Create a new item : param endpoint : endpoint ( API URL ) : type endpoint : str : param data : properties of item to create : type data : dict : param files : Not used . To be implemented : ty...
# We let Requests encode data to json response = self . get_response ( method = 'POST' , endpoint = endpoint , json = data , headers = headers ) resp = self . decode ( response = response ) return resp
def _sanity_check ( self ) : """Check if parameters are okay . Sanity check makes sure each parameter is within an allowable range . Raises : ValueError : Problem with a specific parameter ."""
if any ( self . m1 < 0.0 ) : raise ValueError ( "Mass 1 is negative." ) if any ( self . m2 < 0.0 ) : raise ValueError ( "Mass 2 is negative." ) if any ( self . z <= 0.0 ) : raise ValueError ( "Redshift is zero or negative." ) if any ( self . dist <= 0.0 ) : raise ValueError ( "Distance is zero or negati...
def rddToFileName ( prefix , suffix , timestamp ) : """Return string prefix - time ( . suffix ) > > > rddToFileName ( " spark " , None , 12345678910) ' spark - 12345678910' > > > rddToFileName ( " spark " , " tmp " , 12345678910) ' spark - 12345678910 . tmp '"""
if isinstance ( timestamp , datetime ) : seconds = time . mktime ( timestamp . timetuple ( ) ) timestamp = int ( seconds * 1000 ) + timestamp . microsecond // 1000 if suffix is None : return prefix + "-" + str ( timestamp ) else : return prefix + "-" + str ( timestamp ) + "." + suffix
def make_all ( collector , ** kwargs ) : """Creates all the images in layered order"""
configuration = collector . configuration push = configuration [ "harpoon" ] . do_push only_pushable = configuration [ "harpoon" ] . only_pushable if push : only_pushable = True tag = kwargs . get ( "artifact" , NotSpecified ) if tag is NotSpecified : tag = configuration [ "harpoon" ] . tag images = configurati...
def get_filter_value ( self , column_name ) : """Returns the filtered value for a certain column : param column _ name : The name of the column that we want the value from : return : the filter value of the column"""
for flt , value in zip ( self . filters , self . values ) : if flt . column_name == column_name : return value
def mt_fields ( fields , nomaster = False , onlydefaultlang = False ) : """Returns list of fields for multilanguage fields of model . Examples : print ( mt _ fields ( ' name ' , ' desc ' ) ) [ ' name ' , ' name _ en ' , ' name _ uk ' , ' desc ' , ' desc _ en ' , ' desc _ uk ' ] MyModel . objects . only ( * ...
assert isinstance ( fields , ( list , tuple ) ) fl = [ ] for field in fields : if not nomaster : fl . append ( field ) if onlydefaultlang : fl . append ( '{}_{}' . format ( field , DEFAULT_LANGUAGE ) ) else : for lang in AVAILABLE_LANGUAGES : fl . append ( '{}_{}' . forma...
def getunzipped ( username , repo , thedir ) : """Downloads and unzips a zip file"""
theurl = "https://github.com/" + username + "/" + repo + "/archive/master.zip" name = os . path . join ( thedir , 'temp.zip' ) try : name = urllib . urlretrieve ( theurl , name ) name = os . path . join ( thedir , 'temp.zip' ) except IOError as e : print ( "Can't retrieve %r to %r: %s" % ( theurl , thedir ,...
def _print_level ( level , msg ) : """Print the information in Unicode safe manner ."""
for l in str ( msg . rstrip ( ) ) . split ( "\n" ) : print ( "{0:<9s}{1}" . format ( level , str ( l ) ) )
def _validate_event_listeners ( option , listeners ) : """Validate event listeners"""
if not isinstance ( listeners , Sequence ) : raise TypeError ( "%s must be a list or tuple" % ( option , ) ) for listener in listeners : if not isinstance ( listener , _EventListener ) : raise TypeError ( "Listeners for %s must be either a " "CommandListener, ServerHeartbeatListener, " "ServerListener, ...
def install_config_logstash ( self ) : """install and config logstash : return :"""
if self . prompt_check ( "Download and install logstash" ) : self . logstash_install ( ) if self . prompt_check ( "Configure and autostart logstash" ) : self . logstash_config ( )
def quad_tree ( self ) : """Gets the tile in the Microsoft QuadTree format , converted from TMS"""
value = '' tms_x , tms_y = self . tms tms_y = ( 2 ** self . zoom - 1 ) - tms_y for i in range ( self . zoom , 0 , - 1 ) : digit = 0 mask = 1 << ( i - 1 ) if ( tms_x & mask ) != 0 : digit += 1 if ( tms_y & mask ) != 0 : digit += 2 value += str ( digit ) return value
def _remove_zeros ( votes , fpl , cl , ranking ) : """Remove zeros in IRV voting ."""
for v in votes : for r in v : if r not in fpl : v . remove ( r ) for c in cl : if c not in fpl : if c not in ranking : ranking . append ( ( c , 0 ) )
def session_array ( slots ) : """Return a numpy array mapping sessions to slots - Rows corresponds to sessions - Columns correspond to slots"""
# Flatten the list : this assumes that the sessions do not share slots sessions = sorted ( set ( [ slot . session for slot in slots ] ) ) array = np . zeros ( ( len ( sessions ) , len ( slots ) ) ) for col , slot in enumerate ( slots ) : array [ sessions . index ( slot . session ) , col ] = 1 return array
def print_brokers ( cluster_config , brokers ) : """Print the list of brokers that will be restarted . : param cluster _ config : the cluster configuration : type cluster _ config : map : param brokers : the brokers that will be restarted : type brokers : map of broker ids and host names"""
print ( "Will restart the following brokers in {0}:" . format ( cluster_config . name ) ) for id , host in brokers : print ( " {0}: {1}" . format ( id , host ) )
def snapshot ( self , scheduler = None ) : """Returns a Snapshot containing the sources , relative to the build root . This API is experimental , and subject to change ."""
if isinstance ( self . _sources , EagerFilesetWithSpec ) : snapshot = self . _sources . snapshot if snapshot is not None : return snapshot input_pathglobs = PathGlobs ( tuple ( self . relative_to_buildroot ( ) ) ) return scheduler . product_request ( Snapshot , [ input_pathglobs ] ) [ 0 ]
def getLocalDateAndTime ( date , time , * args , ** kwargs ) : """Get the date and time in the local timezone from date and optionally time"""
localDt = getLocalDatetime ( date , time , * args , ** kwargs ) if time is not None : return ( localDt . date ( ) , localDt . timetz ( ) ) else : return ( localDt . date ( ) , None )
def get_diff ( original , fixed , file_name , original_label = 'original' , fixed_label = 'fixed' ) : """Return text of unified diff between original and fixed ."""
original , fixed = original . splitlines ( True ) , fixed . splitlines ( True ) newline = '\n' from difflib import unified_diff diff = unified_diff ( original , fixed , os . path . join ( original_label , file_name ) , os . path . join ( fixed_label , file_name ) , lineterm = newline ) text = '' for line in diff : ...
def load_app ( target ) : """Load a bottle application from a module and make sure that the import does not affect the current default application , but returns a separate application object . See : func : ` load ` for the target parameter ."""
global NORUN NORUN , nr_old = True , NORUN tmp = default_app . push ( ) # Create a new " default application " try : rv = load ( target ) # Import the target module return rv if callable ( rv ) else tmp finally : default_app . remove ( tmp ) # Remove the temporary added default application NORUN...
def get_roles_by_type ( self , role_type , view = None ) : """Get all roles of a certain type in a service . @ param role _ type : Role type @ param view : View to materialize ( ' full ' or ' summary ' ) @ return : A list of ApiRole objects ."""
return roles . get_roles_by_type ( self . _get_resource_root ( ) , self . name , role_type , self . _get_cluster_name ( ) , view )
def attrs ( self ) : """provide a copy of this player ' s attributes as a dictionary"""
ret = dict ( self . __dict__ ) # obtain copy of internal _ _ dict _ _ del ret [ "_matches" ] # match history is specifically distinguished from player information ( and stored separately ) if self . type != c . COMPUTER : # difficulty only matters for computer playres del ret [ "difficulty" ] return ret
def load_entry_points ( self ) : """Load tasks from entry points ."""
if self . entry_point_group : task_packages = { } for item in pkg_resources . iter_entry_points ( group = self . entry_point_group ) : # Celery 4.2 requires autodiscover to be called with # related _ name for Python 2.7. try : pkg , related_name = item . module_name . rsplit ( '.' , 1 ) ...
def get ( self , tag , default = None ) : """Get a metadata value . Each metadata value is referenced by a ` ` tag ` ` - - a short string such as ` ` ' xlen ' ` ` or ` ` ' audit ' ` ` . In the sidecar file these tag names are prepended with ` ` ' Xmp . pyctools . ' ` ` , which corresponds to a custom namesp...
full_tag = 'Xmp.pyctools.' + tag if full_tag in self . data : return self . data [ full_tag ] return default
def power_on_vm ( name , datacenter = None , service_instance = None ) : '''Powers on a virtual machine specified by it ' s name . name Name of the virtual machine datacenter Datacenter of the virtual machine service _ instance Service instance ( vim . ServiceInstance ) of the vCenter . Default is Non...
log . trace ( 'Powering on virtual machine %s' , name ) vm_properties = [ 'name' , 'summary.runtime.powerState' ] virtual_machine = salt . utils . vmware . get_vm_by_property ( service_instance , name , datacenter = datacenter , vm_properties = vm_properties ) if virtual_machine [ 'summary.runtime.powerState' ] == 'pow...
def split ( src , chunksize = MINWEIGHT ) : """Split a complex fault source in chunks"""
for i , block in enumerate ( block_splitter ( src . iter_ruptures ( ) , chunksize , key = operator . attrgetter ( 'mag' ) ) ) : rup = block [ 0 ] source_id = '%s:%d' % ( src . source_id , i ) amfd = mfd . ArbitraryMFD ( [ rup . mag ] , [ rup . mag_occ_rate ] ) rcs = RuptureCollectionSource ( source_id ,...
def check ( self , paths ) : """Return list of error dicts for all found errors in paths . The default implementation expects ` tool ` , and ` tool _ err _ re ` to be defined . tool : external binary to use for checking . tool _ err _ re : regexp that can match output of ` tool ` - - must provide a groupd...
if not paths : return ( ) cmd_pieces = [ self . tool ] cmd_pieces . extend ( self . tool_args ) return self . _check_std ( paths , cmd_pieces )
def put_scaling_policy ( AutoScalingGroupName = None , PolicyName = None , PolicyType = None , AdjustmentType = None , MinAdjustmentStep = None , MinAdjustmentMagnitude = None , ScalingAdjustment = None , Cooldown = None , MetricAggregationType = None , StepAdjustments = None , EstimatedInstanceWarmup = None ) : ""...
pass
def get ( self , key ) : """Constructs a SyncMapItemContext : param key : The key : returns : twilio . rest . preview . sync . service . sync _ map . sync _ map _ item . SyncMapItemContext : rtype : twilio . rest . preview . sync . service . sync _ map . sync _ map _ item . SyncMapItemContext"""
return SyncMapItemContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , map_sid = self . _solution [ 'map_sid' ] , key = key , )
def _write_data ( data , fp ) : """Write the data section"""
fp . write ( "@data\n" ) def to_str ( x ) : if pandas . isnull ( x ) : return '?' else : return str ( x ) data = data . applymap ( to_str ) n_rows = data . shape [ 0 ] for i in range ( n_rows ) : str_values = list ( data . iloc [ i , : ] . apply ( _check_str_array ) ) line = "," . join (...
def free_params ( self , value ) : """Set the free parameters . Note that this bypasses enforce _ bounds ."""
value = scipy . asarray ( value , dtype = float ) self . K_up_to_date = False self . k . free_params = value [ : self . k . num_free_params ] self . w . free_params = value [ self . k . num_free_params : self . k . num_free_params + self . w . num_free_params ]
def get_joke ( ) : """Returns a joke from the WebKnox one liner API . Returns None if unable to retrieve a joke ."""
page = requests . get ( "https://api.chucknorris.io/jokes/random" ) if page . status_code == 200 : joke = json . loads ( page . content . decode ( "UTF-8" ) ) return joke [ "value" ] return None
def find_by_content_type ( content_type ) : """Find and return a format by content type . : param content _ type : A string describing the internet media type of the format ."""
for format in FORMATS : if content_type in format . content_types : return format raise UnknownFormat ( 'No format found with content type "%s"' % content_type )
def tags ( self , value ) : # pylint : disable - msg = E0102 """Set the tags in the configuraton ( setter )"""
if not isinstance ( value , list ) : raise TypeError self . _config [ 'tags' ] = value
def get_payload_data ( self , token , key ) : """Helper method to get the payload of the JWT token ."""
if self . get_settings ( 'OIDC_ALLOW_UNSECURED_JWT' , False ) : header , payload_data , signature = token . split ( b'.' ) header = json . loads ( smart_text ( b64decode ( header ) ) ) # If config allows unsecured JWTs check the header and return the decoded payload if 'alg' in header and header [ 'alg'...
def diff_segments ( a_segments , b_segments ) : """Performs a diff comparison between two pre - clustered : class : ` deltas . Segment ` trees . In most cases , segmentation takes 100X more time than actually performing the diff . : Parameters : a _ segments : : class : ` deltas . Segment ` An initial seq...
# Match and re - sequence unmatched tokens a_segment_tokens , b_segment_tokens = _cluster_matching_segments ( a_segments , b_segments ) # Perform a simple LCS over unmatched tokens and clusters clustered_ops = sequence_matcher . diff ( a_segment_tokens , b_segment_tokens ) # Return the expanded ( de - clustered ) opera...
def common_properties ( self , build_request , requirements ) : """Given build request and requirements , return properties common to dependency build request and target build properties ."""
# For optimization , we add free unconditional requirements directly , # without using complex algorithsm . # This gives the complex algorithm better chance of caching results . # The exact effect of this " optimization " is no longer clear assert isinstance ( build_request , property_set . PropertySet ) assert isinsta...
def lookups ( self , request , model_admin ) : """Returns a list of tuples . The first element in each tuple is the coded value for the option that will appear in the URL query . The second element is the human - readable name for the option that will appear in the right sidebar ."""
qs = model_admin . get_queryset ( request ) qs . filter ( id__range = ( 1 , 99 ) ) for item in qs : dp = DeviceProtocol . objects . filter ( pk = item . id ) . first ( ) if dp : yield ( dp . pk , dp . app_name )
def get_emodulus ( area_um , deform , medium = "CellCarrier" , channel_width = 20.0 , flow_rate = 0.16 , px_um = 0.34 , temperature = 23.0 , copy = True ) : """Compute apparent Young ' s modulus using a look - up table Parameters area _ um : float or ndarray Apparent ( 2D image ) area [ μm2 ] of the event ( s...
# copy input arrays so we can use in - place calculations deform = np . array ( deform , copy = copy , dtype = float ) area_um = np . array ( area_um , copy = copy , dtype = float ) # Get lut data lut_path = resource_filename ( "dclab.features" , "emodulus_lut.txt" ) with pathlib . Path ( lut_path ) . open ( "rb" ) as ...
def get_elem_type ( elem ) : """Get elem type of soup selection : param elem : a soup element"""
elem_type = None if isinstance ( elem , list ) : if elem [ 0 ] . get ( "type" ) == "radio" : elem_type = "radio" else : raise ValueError ( u"Unknown element type: {}" . format ( elem ) ) elif elem . name == "select" : elem_type = "select" elif elem . name == "input" : elem_type = elem . ...
def get_server_api ( token = None , site = None , cls = None , config = None , ** kwargs ) : """Get the anaconda server api class"""
if not cls : from binstar_client import Binstar cls = Binstar config = config if config is not None else get_config ( site = site ) url = config . get ( 'url' , DEFAULT_URL ) logger . info ( "Using Anaconda API: %s" , url ) if token : logger . debug ( "Using token from command line args" ) elif 'BINSTAR_API...
def read_discrete_trajectory ( filename ) : """Read discrete trajectory from ascii file . The ascii file containing a single column with integer entries is read into an array of integers . Parameters filename : str The filename of the discrete state trajectory file . The filename can either contain the ...
with open ( filename , "r" ) as f : lines = f . read ( ) dtraj = np . fromstring ( lines , dtype = int , sep = "\n" ) return dtraj
def display_drilldown_as_ul ( category , using = 'categories.Category' ) : """Render the category with ancestors and children using the ` ` categories / ul _ tree . html ` ` template . Example : : { % display _ drilldown _ as _ ul " / Grandparent / Parent " % } or : : { % display _ drilldown _ as _ ul cat...
cat = get_category ( category , using ) if cat is None : return { 'category' : cat , 'path' : [ ] } else : return { 'category' : cat , 'path' : drilldown_tree_for_node ( cat ) }
def keep_absolute_resample__roc_auc ( X , y , model_generator , method_name , num_fcounts = 11 ) : """Keep Absolute ( resample ) xlabel = " Max fraction of features kept " ylabel = " ROC AUC " transform = " identity " sort _ order = 12"""
return __run_measure ( measures . keep_resample , X , y , model_generator , method_name , 0 , num_fcounts , sklearn . metrics . roc_auc_score )
def FromTimeString ( cls , time_string , dayfirst = False , gmt_as_timezone = True , timezone = pytz . UTC ) : """Converts a string containing a date and time value into a timestamp . Args : time _ string : String that contains a date and time value . dayfirst : An optional boolean argument . If set to true t...
if not gmt_as_timezone and time_string . endswith ( ' GMT' ) : time_string = '{0:s}UTC' . format ( time_string [ : - 3 ] ) try : # TODO : deprecate the use of dateutil parser . datetime_object = dateutil . parser . parse ( time_string , dayfirst = dayfirst ) except ( TypeError , ValueError ) as exception : ...
def translate ( self , body , params = None ) : """` < Translate SQL into Elasticsearch queries > ` _ : arg body : Specify the query in the ` query ` element ."""
if body in SKIP_IN_PATH : raise ValueError ( "Empty value passed for a required argument 'body'." ) return self . transport . perform_request ( "POST" , "/_sql/translate" , params = params , body = body )
def clear_all ( self ) : """Deletes all ` ` sandsnake ` ` related data from redis . . . warning : : Very expensive and destructive operation . Use with causion"""
keys = self . _analytics_backend . keys ( ) for key in itertools . chain ( * keys ) : with self . _analytics_backend . map ( ) as conn : if key . startswith ( self . _prefix ) : conn . delete ( key )
def get_all ( self ) : """Gets all captured counters . : return : a list with counters ."""
self . _lock . acquire ( ) try : return list ( self . _cache . values ( ) ) finally : self . _lock . release ( )
def thumbnail ( self , dump_to = None ) : """This returns binary data that represents a 128x128 image . If dump _ to is given , attempts to write the image to a file at the given location ."""
headers = { "Authorization" : "token {}" . format ( self . _client . token ) } result = requests . get ( '{}/{}/thumbnail' . format ( self . _client . base_url , OAuthClient . api_endpoint . format ( id = self . id ) ) , headers = headers ) if not result . status_code == 200 : raise ApiError ( 'No thumbnail found f...
def check_fieldsets ( * args , ** kwargs ) : """A Django system check to make sure that , if defined , CONFIG _ FIELDSETS accounts for every entry in settings . CONFIG ."""
if hasattr ( settings , "CONFIG_FIELDSETS" ) and settings . CONFIG_FIELDSETS : inconsistent_fieldnames = get_inconsistent_fieldnames ( ) if inconsistent_fieldnames : return [ checks . Warning ( _ ( "CONSTANCE_CONFIG_FIELDSETS is missing " "field(s) that exists in CONSTANCE_CONFIG." ) , hint = ", " . joi...
def _add_value ( self , skey , vtyp , key , val , _deser , null_allowed ) : """Main method for adding a value to the instance . Does all the checking on type of value and if among allowed values . : param skey : string version of the key : param vtyp : Type of value : param key : original representation of ...
if isinstance ( val , list ) : if ( len ( val ) == 0 or val [ 0 ] is None ) and null_allowed is False : return if isinstance ( vtyp , tuple ) : vtyp = vtyp [ 0 ] if isinstance ( vtyp , list ) : vtype = vtyp [ 0 ] if isinstance ( val , vtype ) : if issubclass ( vtype , Message ) : ...
def get_python_executable ( conn ) : """Try to determine the remote Python version so that it can be used when executing . Avoids the problem of different Python versions , or distros that do not use ` ` python ` ` but do ` ` python3 ` `"""
# executables in order of preference : executables = [ 'python3' , 'python' , 'python2.7' ] for executable in executables : conn . logger . debug ( 'trying to determine remote python executable with %s' % executable ) out , err , code = check ( conn , [ 'which' , executable ] ) if code : conn . logg...
def read ( self , sync_map_format , input_file_path , parameters = None ) : """Read sync map fragments from the given file in the specified format , and add them the current ( this ) sync map . Return ` ` True ` ` if the call succeeded , ` ` False ` ` if an error occurred . : param sync _ map _ format : the...
if sync_map_format is None : self . log_exc ( u"Sync map format is None" , None , True , ValueError ) if sync_map_format not in SyncMapFormat . CODE_TO_CLASS : self . log_exc ( u"Sync map format '%s' is not allowed" % ( sync_map_format ) , None , True , ValueError ) if not gf . file_can_be_read ( input_file_pat...
def read ( self , lpBaseAddress , nSize ) : """Reads from the memory of the process . @ see : L { peek } @ type lpBaseAddress : int @ param lpBaseAddress : Memory address to begin reading . @ type nSize : int @ param nSize : Number of bytes to read . @ rtype : str @ return : Bytes read from the proces...
hProcess = self . get_handle ( win32 . PROCESS_VM_READ | win32 . PROCESS_QUERY_INFORMATION ) if not self . is_buffer ( lpBaseAddress , nSize ) : raise ctypes . WinError ( win32 . ERROR_INVALID_ADDRESS ) data = win32 . ReadProcessMemory ( hProcess , lpBaseAddress , nSize ) if len ( data ) != nSize : raise ctypes...
def start ( self , * msg ) : """Prints an start message"""
self . start_time = datetime . datetime . now ( ) label = colors . purple ( "START" ) self . _msg ( label , * msg )
def _extract_instance_info ( instances ) : '''Given an instance query , return a dict of all instance data'''
ret = { } for instance in instances : # items could be type dict or list ( for stopped EC2 instances ) if isinstance ( instance [ 'instancesSet' ] [ 'item' ] , list ) : for item in instance [ 'instancesSet' ] [ 'item' ] : name = _extract_name_tag ( item ) ret [ name ] = item ...
def send_zipfile ( request , fileList ) : """Create a ZIP file on disk and transmit it in chunks of 8KB , without loading the whole file into memory . A similar approach can be used for large dynamic PDF files ."""
temp = tempfile . TemporaryFile ( ) archive = zipfile . ZipFile ( temp , 'w' , zipfile . ZIP_DEFLATED ) for artist , files in fileList . iteritems ( ) : for f in files : archive . write ( f [ 0 ] , '%s/%s' % ( artist , f [ 1 ] ) ) archive . close ( ) wrapper = FixedFileWrapper ( temp ) response = HttpRespon...
def write_vcf ( path , callset , rename = None , number = None , description = None , fill = None , write_header = True ) : """Preliminary support for writing a VCF file . Currently does not support sample data . Needs further work ."""
names , callset = normalize_callset ( callset ) with open ( path , 'w' ) as vcf_file : if write_header : write_vcf_header ( vcf_file , names , callset = callset , rename = rename , number = number , description = description ) write_vcf_data ( vcf_file , names , callset = callset , rename = rename , fil...
def add_labelset ( self , labelset ) : """Add a set of labels to the plot . : param labelset : the set of labels to be added : type labelset : : class : ` ~ aeneas . plotter . PlotLabelset ` : raises : TypeError : if ` ` labelset ` ` is not an instance of : class : ` ~ aeneas . plotter . PlotLabelset `"""
if not isinstance ( labelset , PlotLabelset ) : self . log_exc ( u"labelset must be an instance of PlotLabelset" , None , True , TypeError ) self . labelsets . append ( labelset ) self . log ( u"Added labelset" )
def get_params ( self ) : """Gets current parameters . Returns ( arg _ params , aux _ params ) A pair of dictionaries each mapping parameter names to NDArray values . This is a merged dictionary of all the parameters in the modules ."""
assert self . binded and self . params_initialized arg_params = dict ( ) aux_params = dict ( ) for module in self . _modules : arg , aux = module . get_params ( ) arg_params . update ( arg ) aux_params . update ( aux ) return ( arg_params , aux_params )
def add_columns ( t0 , t1 ) : """Add columns of table t1 to table t0."""
for colname in t1 . colnames : col = t1 . columns [ colname ] if colname in t0 . columns : continue new_col = Column ( name = col . name , length = len ( t0 ) , dtype = col . dtype ) # shape = col . shape ) t0 . add_column ( new_col )
def make_heading_abstracts ( self , heading_div ) : """An article may contain data for various kinds of abstracts . This method works on those that are included in the Heading . This is displayed after the Authors and Affiliations . Metadata element , content derived from FrontMatter"""
for abstract in self . article . root . xpath ( './front/article-meta/abstract' ) : # Make a copy of the abstract abstract_copy = deepcopy ( abstract ) abstract_copy . tag = 'div' # Abstracts are a rather diverse bunch , keep an eye on them ! title_text = abstract_copy . xpath ( './title[1]/text()' ) ...
def stdlib_list ( version = None ) : """Given a ` ` version ` ` , return a ` ` list ` ` of names of the Python Standard Libraries for that version . These names are obtained from the Sphinx inventory file ( used in : py : mod : ` sphinx . ext . intersphinx ` ) . : param str | None version : The version ( as a...
version = get_canonical_version ( version ) if version is not None else '.' . join ( str ( x ) for x in sys . version_info [ : 2 ] ) module_list_file = os . path . join ( list_dir , "{}.txt" . format ( version ) ) with open ( module_list_file ) as f : result = [ y for y in [ x . strip ( ) for x in f . readlines ( )...
def _get_bonds ( self , mol ) : """Find all the bond in a molcule Args : mol : the molecule . pymatgen Molecule object Returns : List of tuple . Each tuple correspond to a bond represented by the id of the two end atoms ."""
num_atoms = len ( mol ) # index starting from 0 if self . ignore_ionic_bond : covalent_atoms = [ i for i in range ( num_atoms ) if mol . species [ i ] . symbol not in self . ionic_element_list ] else : covalent_atoms = list ( range ( num_atoms ) ) all_pairs = list ( itertools . combinations ( covalent_atoms , 2...
def _build_appid_info ( self , master , dict ) : '''Builds the appid info object @ param master : the master dict @ param dict : the dict object received @ return : the appid info object'''
master [ 'total_crawlids' ] = 0 master [ 'total_pending' ] = 0 master [ 'total_domains' ] = 0 master [ 'crawlids' ] = { } master [ 'appid' ] = dict [ 'appid' ] master [ 'spiderid' ] = dict [ 'spiderid' ] # used for finding total count of domains domain_dict = { } # get all domain queues match_string = '{sid}:*:queue' ....
def evaluate ( self , reference_tag_list , estimated_tag_list = None , estimated_tag_probabilities = None ) : """Evaluate estimated against reference Parameters reference _ tag _ list : list of dict or dcase _ util . containers . MetaDataContainer Reference tag list estimated _ tag _ list : list of dict or ...
if estimated_tag_list is None and estimated_tag_probabilities is None : raise ValueError ( "Nothing to evaluate, give at least estimated_tag_list or estimated_tag_probabilities" ) # Make sure reference _ tag _ list is dcase _ util . containers . MetaDataContainer if not isinstance ( reference_tag_list , dcase_util ...
def _fetch_dimensions ( self , dataset ) : """Declaring available dimensions like this is not mandatory , but nice , especially if they differ from dataset to dataset . If you are using a built in datatype , you can specify the dialect you are expecting , to have values normalized . This scraper will look f...
yield Dimension ( u"date" , label = "Day of the month" ) yield Dimension ( u"month" , datatype = "month" , dialect = "swedish" ) yield Dimension ( u"year" , datatype = "year" )
def nacm_rule_list_rule_rule_type_protocol_operation_rpc_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) nacm = ET . SubElement ( config , "nacm" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-acm" ) rule_list = ET . SubElement ( nacm , "rule-list" ) name_key = ET . SubElement ( rule_list , "name" ) name_key . text = kwargs . pop ( 'name' ) rule = ET . SubElement ( rule_list , "rule...
def community_neighbors ( c_j , reverse_index_rows , unavailable_communities , unavailable_communities_counter ) : """Finds communities with shared nodes to a seed community . Called by mroc . Inputs : - c _ j : The seed community for which we want to find which communities overlap . - reverse _ index _ rows : ...
indices = list ( ) extend = indices . extend for node in c_j : extend ( reverse_index_rows [ node ] ) indices = np . array ( indices ) indices = np . setdiff1d ( indices , unavailable_communities [ : unavailable_communities_counter + 1 ] ) return indices
def get_otp ( hsm , args ) : """Get OTP from YubiKey ."""
if args . no_otp : return None if hsm . version . have_unlock ( ) : if args . stdin : otp = sys . stdin . readline ( ) while otp and otp [ - 1 ] == '\n' : otp = otp [ : - 1 ] else : otp = raw_input ( 'Enter admin YubiKey OTP (press enter to skip) : ' ) if len ( otp ) ...
def first ( self ) : """Return the first result of this Query or None if the result doesn ' t contain any row ."""
results = self . rpc_model . search_read ( self . domain , None , 1 , self . _order_by , self . fields , context = self . context ) return results and results [ 0 ] or None
def set_clock_type ( type ) : """Sets the internal clock type for timing . Profiler shall not have any previous stats . Otherwise an exception is thrown ."""
type = type . upper ( ) if type not in CLOCK_TYPES : raise YappiError ( "Invalid clock type:%s" % ( type ) ) _yappi . set_clock_type ( CLOCK_TYPES [ type ] )
def _chunk_iter_progress ( it , log , prefix ) : """Wrap a chunk iterator for progress logging ."""
n_variants = 0 before_all = time . time ( ) before_chunk = before_all for chunk , chunk_length , chrom , pos in it : after_chunk = time . time ( ) elapsed_chunk = after_chunk - before_chunk elapsed = after_chunk - before_all n_variants += chunk_length chrom = text_type ( chrom , 'utf8' ) message...
def select_location ( self ) : """Select directory ."""
location = osp . normpath ( getexistingdirectory ( self , _ ( "Select directory" ) , self . location ) ) if location : if is_writable ( location ) : self . location = location self . update_location ( )
def set_day ( self , day : int ) -> datetime : """Sets the day value"""
self . value = self . value . replace ( day = day ) return self . value
def _check_compound_pillar_exact_minions ( self , expr , delimiter , greedy ) : '''Return the minions found by looking via compound matcher Disable pillar glob matching'''
return self . _check_compound_minions ( expr , delimiter , greedy , pillar_exact = True )
def get_protocol ( self , protocol ) : """Returns the firstly found protocol that matches to the specified protocol ."""
result = self . get_protocols ( protocol ) if len ( result ) > 0 : return result [ 0 ] return None
def get_all_client_properties ( self , params = None ) : """Get all contacts of client This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param params : search params : return : list"""
return self . _iterate_through_pages ( get_function = self . get_client_properties_per_page , resource = CLIENT_PROPERTIES , ** { 'params' : params } )
def as_dict ( self , decode = False ) : """Return a dictionary containing all the key / value pairs in the hash ."""
res = self . database . hgetall ( self . key ) return decode_dict ( res ) if decode else res
def getFileAndName ( self , * args , ** kwargs ) : '''Give a requested page ( note : the arguments for this call are forwarded to getpage ( ) ) , return the content at the target URL and the filename for the target content as a 2 - tuple ( pgctnt , hName ) for the content at the target URL . The filename spec...
pgctnt , hName , mime = self . getFileNameMime ( * args , ** kwargs ) return pgctnt , hName
def qteNewApplet ( self , appletName : str , appletID : str = None , windowObj : QtmacsWindow = None ) : """Create a new instance of ` ` appletName ` ` and assign it the ` ` appletID ` ` . This method creates a new instance of ` ` appletName ` ` , as registered by the ` ` qteRegisterApplet ` ` method . If an ...
# Use the currently active window if none was specified . if windowObj is None : windowObj = self . qteActiveWindow ( ) if windowObj is None : msg = 'Cannot determine the currently active window.' self . qteLogger . error ( msg , stack_info = True ) return # Determine an automatic applet...
def run_segment_operation ( outdoc , filenames , segments , use_segment_table , operation , result_name = 'RESULT' , preserve = True ) : """Performs an operation ( intersect or union ) across a set of segments . That is , given a set of files each with segment definers DMT - FLAG1, DMT - FLAG2 etc and a list of...
proc_id = table . get_table ( outdoc , lsctables . ProcessTable . tableName ) [ 0 ] . process_id if preserve : indoc = ligolw_add . ligolw_add ( outdoc , filenames ) else : indoc = ligolw_add . ligolw_add ( ligolw . Document ( ) , filenames ) # Start with a segment covering all of time , then # intersect with e...
def emit ( self , record ) : """Emit the log record ."""
self . entries . append ( self . format ( record ) ) if len ( self . entries ) > self . flush_limit and not self . session . auth . renewing : self . log_to_api ( ) self . entries = [ ]