signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def make_viewer ( self , vname , channel ) : """Make a viewer whose type name is ` vname ` and add it to ` channel ` ."""
if vname not in self . viewer_db : raise ValueError ( "I don't know how to build a '%s' viewer" % ( vname ) ) stk_w = channel . widget bnch = self . viewer_db [ vname ] viewer = bnch . vclass ( logger = self . logger , settings = channel . settings ) stk_w . add_widget ( viewer . get_widget ( ) , title = vname ) # ...
def setup_new_conf ( self ) : # pylint : disable = too - many - locals """Setup a new configuration received from a Master arbiter . TODO : perharps we should not accept the configuration or raise an error if we do not find our own configuration data in the data . Thus this should never happen . . . : return ...
# Execute the base class treatment . . . super ( Arbiter , self ) . setup_new_conf ( ) with self . conf_lock : logger . info ( "I received a new configuration from my master" ) # Get the new configuration self . cur_conf = self . new_conf # self _ conf is our own configuration from the alignak environme...
def parse_station_table ( root ) : """Parse station list XML file ."""
stations = [ parse_xml_station ( elem ) for elem in root . findall ( 'station' ) ] return { st . id : st for st in stations }
def _extract_services_list_helper ( services ) : """Extract a OrderedDict of { service : [ ports ] } of the supplied services for use by the other functions . The services object can either be : - None : no services were passed ( an empty dict is returned ) - a list of strings - A dictionary ( optionally ...
if services is None : return { } if isinstance ( services , dict ) : services = services . values ( ) # either extract the list of services from the dictionary , or if # it is a simple string , use that . i . e . works with mixed lists . _s = OrderedDict ( ) for s in services : if isinstance ( s , dict ) an...
def ra_sexegesimal_to_decimal ( self , ra ) : """* Convert a right - ascension from sexegesimal format to decimal degrees . * Precision should be respected . If a float is passed to this method , the same float will be returned ( useful if unclear which format coordinates are in ) . The code will attempt to rea...
import re # TEST TO SEE IF DECIMAL DEGREES PASSED try : ra = float ( ra ) if ra >= 0. and ra <= 360. : self . log . info ( 'RA seems to already be in decimal degrees, returning original value' % locals ( ) ) return float ( ra ) except : pass # REMOVE SURROUNDING WHITESPACE ra = str ( ra ) . ...
def stub_main ( ) : """setuptools blah : it still can ' t run a module as a script entry _ point"""
from google . apputils import run_script_module import butcher . main run_script_module . RunScriptModule ( butcher . main )
def create ( self , name , data_type , dim_sizes ) : """Create a dataset . Args : : name dataset name data _ type type of the data , set to one of the SDC . xxx constants ; dim _ sizes lengths of the dataset dimensions ; a one - dimensional array is specified with an integer , an n - dimensional array...
# Validate args . if isinstance ( dim_sizes , type ( 1 ) ) : # allow k instead of [ k ] # for a 1 - dim arr dim_sizes = [ dim_sizes ] rank = len ( dim_sizes ) buf = _C . array_int32 ( rank ) for n in range ( rank ) : buf [ n ] = dim_sizes [ n ] id = _C . SDcreate ( self . _id , name , data_type , rank , buf ) _...
def to_grpc_address ( target : str ) -> str : """Converts a standard gRPC target to one that is supported by grpcio : param target : the server address . : returns : the converted address ."""
u = urlparse ( target ) if u . scheme == "dns" : raise ValueError ( "dns:// not supported" ) if u . scheme == "unix" : return "unix:" + u . path return u . netloc
def get_assessment_part_bank_session ( self ) : """Gets the ` ` OsidSession ` ` to lookup assessment part / bank mappings for assessment parts . return : ( osid . assessment . authoring . AssessmentPartBankSession ) - an ` ` AssessmentPartBankSession ` ` raise : OperationFailed - unable to complete request ...
if not self . supports_assessment_part_bank ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . AssessmentPartBankSession ( runtime = self . _runtime )
def remove_incomplete_upload ( self , bucket_name , object_name ) : """Remove all in - complete uploads for a given bucket _ name and object _ name . : param bucket _ name : Bucket to drop incomplete uploads : param object _ name : Name of object to remove incomplete uploads : return : None"""
is_valid_bucket_name ( bucket_name ) is_non_empty_string ( object_name ) recursive = True uploads = self . _list_incomplete_uploads ( bucket_name , object_name , recursive , is_aggregate_size = False ) for upload in uploads : if object_name == upload . object_name : self . _remove_incomplete_upload ( bucket...
def hints ( self , ** kwargs ) : """Use this method to update hints value of the underlying query example : queryset . hints ( permissive = False )"""
new_query = self . query . clone ( ) new_query . hints . update ( kwargs ) return self . _clone ( query = new_query )
def renders_impl ( self , template_content , context , at_encoding = anytemplate . compat . ENCODING , ** kwargs ) : """Render given template string and return the result . : param template _ content : Template content : param context : A dict or dict - like object to instantiate given template file : param...
tmpdir = os . environ . get ( "TMPDIR" , "/tmp" ) res = template_content try : ( ofd , opath ) = tempfile . mkstemp ( prefix = "at-tenjin-tmpl-" , dir = tmpdir ) os . write ( ofd , template_content . encode ( at_encoding ) ) os . close ( ofd ) res = self . render_impl ( opath , context , ** kwargs ) exc...
def add_ssl_termination ( self , loadbalancer , securePort , privatekey , certificate , intermediateCertificate , enabled = True , secureTrafficOnly = False ) : """Adds SSL termination information to the load balancer . If SSL termination has already been configured , it is updated with the supplied settings ."""
uri = "/loadbalancers/%s/ssltermination" % utils . get_id ( loadbalancer ) req_body = { "sslTermination" : { "certificate" : certificate , "enabled" : enabled , "secureTrafficOnly" : secureTrafficOnly , "privatekey" : privatekey , "intermediateCertificate" : intermediateCertificate , "securePort" : securePort , } } res...
def split_call ( lines , open_paren_line = 0 ) : """Returns a 2 - tuple where the first element is the list of lines from the first open paren in lines to the matching closed paren . The second element is all remaining lines in a list ."""
num_open = 0 num_closed = 0 for i , line in enumerate ( lines ) : c = line . count ( '(' ) num_open += c if not c and i == open_paren_line : raise Exception ( 'Exception open parenthesis in line %d but there is not one there: %s' % ( i , str ( lines ) ) ) num_closed += line . count ( ')' ) i...
def _get_data_bytes_or_stream_only ( param_name , param_value ) : '''Validates the request body passed in is a stream / file - like or bytes object .'''
if param_value is None : return b'' if isinstance ( param_value , bytes ) or hasattr ( param_value , 'read' ) : return param_value raise TypeError ( _ERROR_VALUE_SHOULD_BE_BYTES_OR_STREAM . format ( param_name ) )
def com_google_fonts_check_fontv ( ttFont ) : """Check for font - v versioning"""
from fontv . libfv import FontVersion fv = FontVersion ( ttFont ) if fv . version and ( fv . is_development or fv . is_release ) : yield PASS , "Font version string looks GREAT!" else : yield INFO , ( "Version string is: \"{}\"\n" "The version string must ideally include a git commit hash" " and either a 'dev' ...
def build ( self , response ) : """Deserialize the returned objects and return either a single Zenpy object , or a ResultGenerator in the case of multiple results . : param response : the requests Response object ."""
response_json = response . json ( ) # Special case for ticket audits . if get_endpoint_path ( self . api , response ) . startswith ( '/ticket_audits.json' ) : return TicketAuditGenerator ( self , response_json ) zenpy_objects = self . deserialize ( response_json ) # Collection of objects ( eg , users / tickets ) pl...
def parse_targets ( name = None , pkgs = None , sources = None , saltenv = 'base' , normalize = True , ** kwargs ) : '''Parses the input to pkg . install and returns back the package ( s ) to be installed . Returns a list of packages , as well as a string noting whether the packages are to come from a repositor...
if '__env__' in kwargs : # " env " is not supported ; Use " saltenv " . kwargs . pop ( '__env__' ) if __grains__ [ 'os' ] == 'MacOS' and sources : log . warning ( 'Parameter "sources" ignored on MacOS hosts.' ) version = kwargs . get ( 'version' ) if pkgs and sources : log . error ( 'Only one of "pkgs" and ...
def is_correct ( self ) : """Check if this object configuration is correct : : * Check our own specific properties * Call our parent class is _ correct checker : return : True if the configuration is correct , otherwise False : rtype : bool"""
state = True # _ internal _ host _ check is for having an host check result # without running a check plugin if self . command_name . startswith ( '_internal_host_check' ) : # Command line may contain : [ state _ id ] [ ; output ] parameters = self . command_line . split ( ';' ) if len ( parameters ) < 2 : ...
def _update_dict ( self , to_dict , from_dict ) : """Recursively merges the fields for two dictionaries . Args : to _ dict ( dict ) : The dictionary onto which the merge is executed . from _ dict ( dict ) : The dictionary merged into to _ dict"""
for key , value in from_dict . items ( ) : if key in to_dict and isinstance ( to_dict [ key ] , dict ) and isinstance ( from_dict [ key ] , dict ) : self . _update_dict ( to_dict [ key ] , from_dict [ key ] ) else : to_dict [ key ] = from_dict [ key ]
def set_batch_commitlog ( self , enabled = False ) : """The batch _ commitlog option gives an easier way to switch to batch commitlog ( since it requires setting 2 options and unsetting one ) ."""
if enabled : values = { "commitlog_sync" : "batch" , "commitlog_sync_batch_window_in_ms" : 5 , "commitlog_sync_period_in_ms" : None } else : values = { "commitlog_sync" : "periodic" , "commitlog_sync_batch_window_in_ms" : None , "commitlog_sync_period_in_ms" : 10000 } self . set_configuration_options ( values )
def document ( self ) : """Read preference as a document ."""
doc = { 'mode' : self . __mongos_mode } if self . __tag_sets not in ( None , [ { } ] ) : doc [ 'tags' ] = self . __tag_sets if self . __max_staleness != - 1 : doc [ 'maxStalenessSeconds' ] = self . __max_staleness return doc
def get_tagged ( self , tags ) : """Tag format . The format for the tags list is tuples for tags : mongos , config , shard , secondary tags of the form ( tag , number ) , e . g . ( ' mongos ' , 2 ) which references the second mongos in the list . For all other tags , it is simply the string , e . g . ' prim...
# if tags is a simple string , make it a list ( note : tuples like # ( ' mongos ' , 2 ) must be in a surrounding list ) if not hasattr ( tags , '__iter__' ) and type ( tags ) == str : tags = [ tags ] nodes = set ( self . cluster_tags [ 'all' ] ) for tag in tags : if re . match ( r"\w+ \d{1,2}" , tag ) : # speci...
def join ( self , words ) : """Capitalize the first alpha character in the reply and the first alpha character that follows one of [ . ? ! ] and a space ."""
chars = list ( u"" . join ( words ) ) start = True for i in xrange ( len ( chars ) ) : char = chars [ i ] if char . isalpha ( ) : if start : chars [ i ] = char . upper ( ) else : chars [ i ] = char . lower ( ) start = False else : if i > 2 and chars [ ...
def get_stellar_toml ( domain , allow_http = False ) : """Retrieve the stellar . toml file from a given domain . Retrieve the stellar . toml file for information about interacting with Stellar ' s federation protocol for a given Stellar Anchor ( specified by a domain ) . : param str domain : The domain the ...
toml_link = '/.well-known/stellar.toml' if allow_http : protocol = 'http://' else : protocol = 'https://' url_list = [ '' , 'www.' , 'stellar.' ] url_list = [ protocol + url + domain + toml_link for url in url_list ] for url in url_list : r = requests . get ( url ) if r . status_code == 200 : re...
def find_shared_dna ( self , individual1 , individual2 , cM_threshold = 0.75 , snp_threshold = 1100 , shared_genes = False , save_output = True , ) : """Find the shared DNA between two individuals . Computes the genetic distance in centiMorgans ( cMs ) between SNPs using the HapMap Phase II GRCh37 genetic map ....
one_chrom_shared_genes = pd . DataFrame ( ) two_chrom_shared_genes = pd . DataFrame ( ) self . _remap_snps_to_GRCh37 ( [ individual1 , individual2 ] ) df = individual1 . snps df = df . join ( individual2 . snps [ "genotype" ] , rsuffix = "2" , how = "inner" ) genotype1 = "genotype_" + individual1 . get_var_name ( ) gen...
def info ( self , path = "/" , # type : Text namespaces = None , # type : Optional [ Collection [ Text ] ] ** kwargs # type : Any ) : # type : ( . . . ) - > Iterator [ Tuple [ Text , Info ] ] """Walk a filesystem , yielding path and ` Info ` of resources . Arguments : path ( str ) : A path to a directory . na...
walker = self . _make_walker ( ** kwargs ) return walker . info ( self . fs , path = path , namespaces = namespaces )
def authenticate_device ( self , api_token , device_token , email = None , user_url = None , override = False , fetch = True ) : """Set credentials for Device authentication . Args : api _ token ( str ) : Token issued to your Application through the Gem Developer Console . device _ token ( str ) : Physical ...
if ( self . context . has_auth_params ( 'Gem-Device' ) and not override ) : raise OverrideError ( 'Gem-Device' ) if ( not api_token or not device_token or ( not email and not user_url ) or not self . context . authorize ( 'Gem-Device' , api_token = api_token , user_email = email , user_url = user_url , device_token...
def addLineAnnot ( self , p1 , p2 ) : """Add ' Line ' annot for points p1 and p2."""
CheckParent ( self ) val = _fitz . Page_addLineAnnot ( self , p1 , p2 ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
def CreateRetryTask ( self ) : """Creates a task that to retry a previously abandoned task . Returns : Task : a task that was abandoned but should be retried or None if there are no abandoned tasks that should be retried ."""
with self . _lock : abandoned_task = self . _GetTaskPendingRetry ( ) if not abandoned_task : return None # The abandoned task is kept in _ tasks _ abandoned so it can be still # identified in CheckTaskToMerge and UpdateTaskAsPendingMerge . retry_task = abandoned_task . CreateRetryTask ( ) ...
def check_identical_chars ( input_string : str ) -> bool : """This Python function checks if all characters in a string are identical . Example : check _ identical _ chars ( ' python ' ) - > False check _ identical _ chars ( ' aaa ' ) - > True check _ identical _ chars ( ' data ' ) - > False Args : inpu...
string_length = len ( input_string ) for index in range ( 1 , string_length ) : if input_string [ index ] != input_string [ 0 ] : return False return True
def describe ( self ) : """Describes this Categorical Returns description : ` DataFrame ` A dataframe with frequency and counts by category ."""
counts = self . value_counts ( dropna = False ) freqs = counts / float ( counts . sum ( ) ) from pandas . core . reshape . concat import concat result = concat ( [ counts , freqs ] , axis = 1 ) result . columns = [ 'counts' , 'freqs' ] result . index . name = 'categories' return result
def bprecess ( ra0 , dec0 , mu_radec = None , parallax = None , rad_vel = None , epoch = None ) : """NAME : BPRECESS PURPOSE : Precess positions from J2000.0 ( FK5 ) to B1950.0 ( FK4) EXPLANATION : Calculates the mean place of a star at B1950.0 on the FK4 system from the mean place at J2000.0 on the FK5...
scal = True if isinstance ( ra0 , ndarray ) : ra = ra0 dec = dec0 n = ra . size scal = False else : n = 1 ra = array ( [ ra0 ] ) dec = array ( [ dec0 ] ) if rad_vel is None : rad_vel = zeros ( n ) else : if not isinstance ( rad_vel , ndarray ) : rad_vel = array ( [ rad_vel ] ...
def get_context_data ( self , ** kwargs ) : """Update context data with list of RPC methods of the current entry point . Will be used to display methods documentation page"""
kwargs . update ( { 'methods' : registry . get_all_methods ( self . entry_point , sort_methods = True ) , } ) return super ( RPCEntryPoint , self ) . get_context_data ( ** kwargs )
def _get_electricity_info_html ( apart_id , meter_room ) : """get html : param apart _ id : 栋数 : param meter _ room : 宿舍号"""
if apart . get ( apart_id ) is None : raise KeyError ( 'not support the apart_id= ' + apart_id ) post_data = { 'action' : 'search' , 'apartID' : apart . get ( apart_id ) , 'meter_room' : apart_id + meter_room } r = requests . post ( 'http://202.192.252.140/index.asp' , data = post_data ) return r . content . decode...
def get_instances ( self ) : """Returns a flat list of the names of services created in this space ."""
services = [ ] for resource in self . _get_instances ( ) : services . append ( resource [ 'entity' ] [ 'name' ] ) return services
def template_ds ( basedir , varname , vars , lookup_fatal = True , depth = 0 ) : '''templates a data structure by traversing it and substituting for other data structures'''
if isinstance ( varname , basestring ) : m = _varFind ( basedir , varname , vars , lookup_fatal , depth ) if not m : return varname if m [ 'start' ] == 0 and m [ 'end' ] == len ( varname ) : if m [ 'replacement' ] is not None : return template_ds ( basedir , m [ 'replacement' ] ,...
def get ( self , what ) : """Get the ANSI code for ' what ' Returns an empty string if disabled / not found"""
if self . enabled : if what in self . colors : return self . colors [ what ] return ''
async def request_name_async ( self , bus_name , flags , error = None , timeout = DBUS . TIMEOUT_USE_DEFAULT ) : "registers a bus name ."
assert self . loop != None , "no event loop to attach coroutine to" if not self . _registered_bus_names_listeners : self . _registered_bus_names_listeners = True # do first in case of reentrant call await self . connection . bus_add_match_action_async ( rule = "type=signal,interface=org.freedesktop.DBus,mem...
def close ( self ) : """Close this metrics repository ."""
for reporter in self . _reporters : reporter . close ( ) self . _metrics . clear ( )
def parse_belscript ( lines ) : """Lines from the BELScript - can be an iterator or list yields Nanopubs in nanopubs _ bel - 1.0.0 format"""
nanopubs_metadata = { } annotations = { } assertions = [ ] # # Turn a list into an iterator # if not isinstance ( lines , collections . Iterator ) : # lines = iter ( lines ) line_num = 0 # for line in preprocess _ belscript ( lines ) : for line in set_single_line ( lines ) : line_num += 1 # Get rid of trailing ...
def _run_soft_delete ( self ) : """Perform the actual delete query on this model instance ."""
query = self . new_query ( ) . where ( self . get_key_name ( ) , self . get_key ( ) ) time = self . fresh_timestamp ( ) setattr ( self , self . get_deleted_at_column ( ) , time ) query . update ( { self . get_deleted_at_column ( ) : self . from_datetime ( time ) } )
def unwrap ( self , value , session = None ) : '''Unwrap value using the unwrap function from ` ` EnumField . item _ type ` ` . Since unwrap validation could not happen in is _ valid _ wrap , it happens in this function .'''
self . validate_unwrap ( value ) value = self . item_type . unwrap ( value , session = session ) for val in self . values : if val == value : return val self . _fail_validation ( value , 'Value was not in the enum values' )
def run ( self ) : """Starts the server run loop and returns after the server shuts down due to a shutdown - request , Harakiri signal , or unhandled exception . See the documentation for ` Server . main ` for full details on the chain of ` Server ` method calls ."""
self . logger . info ( 'Service "{service}" server starting up, pysoa version {pysoa}, listening on transport {transport}.' . format ( service = self . service_name , pysoa = pysoa . version . __version__ , transport = self . transport , ) ) self . setup ( ) self . metrics . commit ( ) if self . _async_event_loop_threa...
def apply_patch ( self ) : """apply adjustment patch for storage"""
patch = self . patches . get ( self . storage . __class__ . __name__ ) if patch : patch . apply ( self )
def ReadHuntClientResourcesStats ( self , hunt_id ) : """Read / calculate hunt client resources stats ."""
result = rdf_stats . ClientResourcesStats ( ) for f in self . _GetHuntFlows ( hunt_id ) : cr = rdf_client_stats . ClientResources ( session_id = "%s/%s" % ( f . client_id , f . flow_id ) , client_id = f . client_id , cpu_usage = f . cpu_time_used , network_bytes_sent = f . network_bytes_sent ) result . Register...
def start_raylet_monitor ( redis_address , stdout_file = None , stderr_file = None , redis_password = None , config = None ) : """Run a process to monitor the other processes . Args : redis _ address ( str ) : The address that the Redis server is listening on . stdout _ file : A file handle opened for writing...
gcs_ip_address , gcs_port = redis_address . split ( ":" ) redis_password = redis_password or "" config = config or { } config_str = "," . join ( [ "{},{}" . format ( * kv ) for kv in config . items ( ) ] ) command = [ RAYLET_MONITOR_EXECUTABLE , "--redis_address={}" . format ( gcs_ip_address ) , "--redis_port={}" . for...
def warm_night_frequency ( tasmin , thresh = '22 degC' , freq = 'YS' ) : r"""Frequency of extreme warm nights Return the number of days with tasmin > thresh per period Parameters tasmin : xarray . DataArray Minimum daily temperature [ ° C ] or [ K ] thresh : str Threshold temperature on which to base ev...
thresh = utils . convert_units_to ( thresh , tasmin , ) events = ( tasmin > thresh ) * 1 return events . resample ( time = freq ) . sum ( dim = 'time' )
def get_urls ( self ) : """Appends the custom will _ not _ clone url to the admin site"""
not_clone_url = [ url ( r'^(.+)/will_not_clone/$' , admin . site . admin_view ( self . will_not_clone ) ) ] restore_url = [ url ( r'^(.+)/restore/$' , admin . site . admin_view ( self . restore ) ) ] return not_clone_url + restore_url + super ( VersionedAdmin , self ) . get_urls ( )
def get_annotation_from_schema ( annotation : Any , schema : Schema ) -> Type [ Any ] : """Get an annotation with validation implemented for numbers and strings based on the schema . : param annotation : an annotation from a field specification , as ` ` str ` ` , ` ` ConstrainedStr ` ` : param schema : an insta...
if isinstance ( annotation , type ) : attrs : Optional [ Tuple [ str , ... ] ] = None constraint_func : Optional [ Callable [ ... , type ] ] = None if issubclass ( annotation , str ) and not issubclass ( annotation , ( EmailStr , DSN , UrlStr , ConstrainedStr ) ) : attrs = ( 'max_length' , 'min_leng...
def on_decks ( self , * args ) : """Inform the cards of their deck and their index within the deck ; extend the ` ` _ hint _ offsets ` ` properties as needed ; and trigger a layout ."""
if None in ( self . canvas , self . decks , self . deck_x_hint_offsets , self . deck_y_hint_offsets ) : Clock . schedule_once ( self . on_decks , 0 ) return self . clear_widgets ( ) decknum = 0 for deck in self . decks : cardnum = 0 for card in deck : if not isinstance ( card , Card ) : ...
def _generate_provisional_name ( q , astrom_header , fits_header ) : """Generates a name for an object given the information in its astrom observation header and FITS header . : param q : a queue of provisional names to return . : type q : Queue : param astrom _ header : : param fits _ header :"""
while True : ef = get_epoch_field ( astrom_header , fits_header ) epoch_field = ef [ 0 ] + ef [ 1 ] count = storage . increment_object_counter ( storage . MEASURE3 , epoch_field ) try : q . put ( ef [ 1 ] + count ) except : break
def run ( self ) -> None : """processes entries in the queue until told to stop"""
while not self . cleanup : try : result , test , additional_info = self . result_queue . get ( timeout = 1 ) except queue . Empty : continue self . result_queue . task_done ( ) if result == TestState . serialization_failure : test = self . tests [ test ] warnings . warn (...
def insert_top ( self , node ) : """Insert statements at the top of the function body . Note that multiple calls to ` insert _ top ` will result in the statements being prepended in that order ; this is different behavior from ` prepend ` . Args : node : The statement to prepend . Raises : ValueError : ...
if not isinstance ( node , grammar . STATEMENTS ) : raise ValueError self . to_insert_top . append ( node )
def CreateTasksFilter ( pc , tasks ) : """Create property collector filter for tasks"""
if not tasks : return None # First create the object specification as the task object . objspecs = [ vmodl . query . PropertyCollector . ObjectSpec ( obj = task ) for task in tasks ] # Next , create the property specification as the state . propspec = vmodl . query . PropertyCollector . PropertySpec ( type = vim . ...
def get_file_format ( self ) : """Get the file format description . This describes the type of data stored on disk ."""
# Have cached file format ? if self . _file_fmt is not None : return self . _file_fmt # Make the call to retrieve it . desc = AudioStreamBasicDescription ( ) size = ctypes . c_int ( ctypes . sizeof ( desc ) ) check ( _coreaudio . ExtAudioFileGetProperty ( self . _obj , PROP_FILE_DATA_FORMAT , ctypes . byref ( size ...
def get_experiment_time ( port ) : '''get the startTime and endTime of an experiment'''
response = rest_get ( experiment_url ( port ) , REST_TIME_OUT ) if response and check_response ( response ) : content = convert_time_stamp_to_date ( json . loads ( response . text ) ) return content . get ( 'startTime' ) , content . get ( 'endTime' ) return None , None
def make_release ( ctx , bump = None , skip_local = False , skip_test = False , skip_pypi = False , skip_isort = False ) : """Make and upload the release ."""
colorama . init ( ) text . title ( "Minchin 'Make Release' for Python Projects v{}" . format ( __version__ ) ) print ( ) text . subtitle ( "Configuration" ) extra_keys = [ 'here' , 'source' , 'test' , 'docs' , 'version' , 'module_name' , ] check_configuration ( ctx , 'releaser' , extra_keys ) check_existence ( ctx . re...
def _generate_initial_model ( self ) : """Creates the initial model for the optimistation . Raises TypeError Raised if the model failed to build . This could be due to parameters being passed to the specification in the wrong format ."""
initial_parameters = [ p . current_value for p in self . current_parameters ] try : initial_model = self . specification ( * initial_parameters ) except TypeError : raise TypeError ( 'Failed to build initial model. Make sure that the input ' 'parameters match the number and order of arguements ' 'expected by th...
def get_value ( self , meta , base_model_meta , mcs_args : McsArgs ) : """overridden to merge with inherited value"""
if mcs_args . Meta . abstract : return None value = getattr ( base_model_meta , self . name , { } ) or { } value . update ( getattr ( meta , self . name , { } ) ) return value
def turbulent_Petukhov_Kirillov_Popov ( Re = None , Pr = None , fd = None ) : r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [ 2 ] _ and [ 3 ] _ as in [ 1 ] _ . . . math : : Nu = \ frac { ( f / 8 ) RePr } { C + 12.7 ( f / 8 ) ^ { 1/2 } ( Pr ^ { 2/3 } - 1 ) } \ \ C...
C = 1.07 + 900. / Re - ( 0.63 / ( 1. + 10. * Pr ) ) return ( fd / 8. ) * Re * Pr / ( C + 12.7 * ( fd / 8. ) ** 0.5 * ( Pr ** ( 2 / 3. ) - 1. ) )
def train ( symbol_data , train_iterator , valid_iterator , data_column_names , target_names ) : """Train cnn model Parameters symbol _ data : symbol train _ iterator : DataIter Train DataIter valid _ iterator : DataIter Valid DataIter data _ column _ names : list of str Defaults to ( ' data ' ) for...
devs = mx . cpu ( ) # default setting if args . gpus is not None : for i in args . gpus . split ( ',' ) : mx . gpu ( int ( i ) ) devs = mx . gpu ( ) module = mx . mod . Module ( symbol_data , data_names = data_column_names , label_names = target_names , context = devs ) module . fit ( train_data = train...
def _guess_format ( path ) : """Guess the format of a dataset based on its filename / filenames ."""
if os . path . isdir ( path ) : return 'dir-npy' if path . endswith ( '.h5' ) or path . endswith ( '.hdf5' ) : # TODO : Check for mdtraj . h5 file return 'hdf5' # TODO : What about a list of trajectories , e . g . from command line nargs = ' + ' return 'mdtraj'
def commands ( self ) : """Returns a list of commands supported by the motor controller ."""
self . _commands , value = self . get_attr_set ( self . _commands , 'commands' ) return value
def _get_1f_sum_scans ( self , d , freq ) : """Sum counts in each frequency bin over 1f scans ."""
# combine scans : values with same frequency unique_freq = np . unique ( freq ) sum_scans = [ [ ] for i in range ( len ( d ) ) ] for f in unique_freq : tag = freq == f for i in range ( len ( d ) ) : sum_scans [ i ] . append ( np . sum ( d [ i ] [ tag ] ) ) return ( np . array ( unique_freq ) , np . arra...
def is_compatible ( self , model , version ) : """Check if this flag is compatible with a YubiKey of version ' ver ' ."""
if not model in self . models : return False if self . max_ykver : return ( version >= self . min_ykver and version <= self . max_ykver ) else : return version >= self . min_ykver
def enable_rm_ha ( self , new_rm_host_id , zk_service_name = None ) : """Enable high availability for a YARN ResourceManager . @ param new _ rm _ host _ id : id of the host where the second ResourceManager will be added . @ param zk _ service _ name : Name of the ZooKeeper service to use for auto - failover ....
args = dict ( newRmHostId = new_rm_host_id , zkServiceName = zk_service_name ) return self . _cmd ( 'enableRmHa' , data = args )
def _run_sync ( self , method : Callable , * args , ** kwargs ) -> Any : """Utility method to run commands synchronously for testing ."""
if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , ** kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . lo...
def plot_groups_unplaced ( self , fout_dir = "." , ** kws_pltargs ) : """Plot GO DAGs for groups of user GOs which are not in a section ."""
hdrgos = self . grprobj . get_hdrgos_unplaced ( ) pltargs = PltGroupedGosArgs ( self . grprobj , fout_dir = fout_dir , ** kws_pltargs ) return self . _plot_groups_hdrgos ( hdrgos , pltargs )
def deactivate ( self ) : """Deactivates the logical volume . * Raises : * * HandleError"""
self . open ( ) d = lvm_lv_deactivate ( self . handle ) self . close ( ) if d != 0 : raise CommitError ( "Failed to deactivate LV." )
from collections import Counter def attach_tuple_frequency ( tuple_list ) : """Append the frequency of each tuple in the provided list of tuples . This function updates each tuple in the list with an additional element , representing the number of times the tuple appears in the list . > > > attach _ tuple _ f...
freq_list = [ ( * tup , freq ) for ( tup , freq ) in Counter ( tuple_list ) . items ( ) ] return str ( freq_list )
def get_function_by_name ( full_name ) : """RETURN FUNCTION"""
# IMPORT MODULE FOR HANDLER path = full_name . split ( "." ) function_name = path [ - 1 ] path = "." . join ( path [ : - 1 ] ) constructor = None try : temp = __import__ ( path , globals ( ) , locals ( ) , [ function_name ] , - 1 ) output = object . __getattribute__ ( temp , function_name ) return output ex...
def close ( self ) : """Closes the ssh connection ."""
if 'isLive' in self . __dict__ and self . isLive : self . transport . close ( ) self . isLive = False
def _create_handler ( self , handler_class , level ) : """Create an handler for at specific level ."""
if handler_class == logging . StreamHandler : handler = handler_class ( ) handler . setLevel ( level ) elif handler_class == logging . handlers . SysLogHandler : handler = handler_class ( address = '/dev/log' ) handler . setLevel ( level ) elif handler_class == logging . handlers . TimedRotatingFileHand...
def link_to ( self , source , transformation = None ) : """Kervi values may be linked together . A KerviValue is configured to be either an input or output . When an output value is linked to an input value the input will become an observer of the output . Every time the output value change it will notify the...
if isinstance ( source , KerviValue ) : if source . is_input and not self . is_input : self . add_observer ( source , transformation ) elif not source . is_input and self . is_input : source . add_observer ( self , transformation ) else : raise Exception ( "input/output mismatch in k...
def read_folder ( directory ) : """read text files in directory and returns them as array Args : directory : where the text files are Returns : Array of text"""
res = [ ] for filename in os . listdir ( directory ) : with io . open ( os . path . join ( directory , filename ) , encoding = "utf-8" ) as f : content = f . read ( ) res . append ( content ) return res
def arxiv_categories ( self , key , value ) : """Populate the ` ` arxiv _ categories ` ` key . Also populates the ` ` inspire _ categories ` ` key through side effects ."""
def _is_arxiv ( category ) : return category in valid_arxiv_categories ( ) def _is_inspire ( category ) : schema = load_schema ( 'elements/inspire_field' ) valid_inspire_categories = schema [ 'properties' ] [ 'term' ] [ 'enum' ] return category in valid_inspire_categories def _normalize ( a_value ) : ...
def next_token ( self , tokenum , value , scol ) : """Determine what to do with the next token"""
# Make self . current reflect these values self . current . set ( tokenum , value , scol ) # Determine indent _ type based on this token if self . current . tokenum == INDENT and self . current . value : self . indent_type = self . current . value [ 0 ] # Only proceed if we shouldn ' t ignore this token if not self...
def track ( self , delta_pixels , push_target = False , adj_fov = False ) : """This causes the camera to translate forward into the scene . This is also called " dollying " or " tracking " in some software packages . Passing in a negative delta causes the opposite motion . If ` ` push _ target ' ' is True , t...
direction = self . target - self . position distance_from_target = direction . length ( ) direction = direction . normalized ( ) initial_ht = frustum_height_at_distance ( self . fov_deg , distance_from_target ) # # print ( " frustum height at distance % . 4f is % . 4f " % ( # # distance _ from _ target , initial _ ht )...
def token_generator ( self , texts , ** kwargs ) : """Yields tokens from texts as ` ( text _ idx , character ) `"""
for text_idx , text in enumerate ( texts ) : if self . lower : text = text . lower ( ) for char in text : yield text_idx , char
def next_frame_tiny ( ) : """Tiny for testing ."""
hparams = next_frame_basic_deterministic ( ) hparams . hidden_size = 32 hparams . num_hidden_layers = 1 hparams . num_compress_steps = 2 hparams . filter_double_steps = 1 return hparams
def resolve ( self , pid , vendorSpecific = None ) : """See Also : resolveResponse ( ) Args : pid : vendorSpecific : Returns :"""
response = self . resolveResponse ( pid , vendorSpecific ) return self . _read_dataone_type_response ( response , 'ObjectLocationList' , response_is_303_redirect = True )
def set_template ( self , template ) : """Sets template to be used when generating output : param template TEmplate instance : type instance of BasicTemplate"""
if isinstance ( template , templates . BasicTemplate ) : self . template = template else : raise TypeError ( 'converter#set_template:' 'Template must inherit from BasicTemplate' )
def send ( self , task_path , args , kwargs ) : """Create the message object and pass it to the actual sender ."""
message = { 'task_path' : task_path , 'capture_response' : self . capture_response , 'response_id' : self . response_id , 'args' : args , 'kwargs' : kwargs } self . _send ( message ) return self
def _generate_training_data ( self , X1 , X2 , num_training_samples ) : """Generate training data for the classifier . Compute the correlation , do the normalization if necessary , and compute the kernel matrix if the classifier is sklearn . svm . SVC with precomputed kernel . Parameters X1 : a list of nu...
if not ( isinstance ( self . clf , sklearn . svm . SVC ) and self . clf . kernel == 'precomputed' ) : # correlation computation corr_data = self . _prepare_corerelation_data ( X1 , X2 ) # normalization normalized_corr_data = self . _normalize_correlation_data ( corr_data , self . epochs_per_subj ) # tra...
def init ( library : typing . Union [ str , types . ModuleType ] ) -> None : '''Must be called at some point after import and before your event loop is run . Populates the asynclib instance of _ AsyncLib with methods relevant to the async library you are using . The supported libraries at the moment are : ...
if isinstance ( library , types . ModuleType ) : library = library . __name__ if library not in manager . _handlers : raise ValueError ( "Possible values are <{}>, not <{}>" . format ( manager . _handlers . keys ( ) , library ) ) manager . init ( library , asynclib ) asynclib . lib_name = library asynclib . _in...
def _kmeans ( y , k = 5 ) : """Helper function to do kmeans in one dimension"""
y = y * 1. # KMEANS needs float or double dtype centroids = KMEANS ( y , k ) [ 0 ] centroids . sort ( ) try : class_ids = np . abs ( y - centroids ) . argmin ( axis = 1 ) except : class_ids = np . abs ( y [ : , np . newaxis ] - centroids ) . argmin ( axis = 1 ) uc = np . unique ( class_ids ) cuts = np . array (...
def cli ( env , snapshot_id ) : """Deletes a snapshot on a given volume"""
block_manager = SoftLayer . BlockStorageManager ( env . client ) deleted = block_manager . delete_snapshot ( snapshot_id ) if deleted : click . echo ( 'Snapshot %s deleted' % snapshot_id )
async def serviceClientMsgs ( self , limit : int ) -> int : """Process ` limit ` number of messages from the clientInBox . : param limit : the maximum number of messages to process : return : the number of messages successfully processed"""
c = await self . clientstack . service ( limit , self . quota_control . client_quota ) self . metrics . add_event ( MetricsName . CLIENT_STACK_MESSAGES_PROCESSED , c ) await self . processClientInBox ( ) return c
def _resolve_plugins ( plugins ) : """Resolve embedded plugins from the wheel ' s library directory . For internal module use only . : param str plugins : The plugin . library . paths value"""
import os from sys import platform # Location of _ _ init _ _ . py and the embedded library directory basedir = os . path . dirname ( __file__ ) if platform in ( 'win32' , 'cygwin' ) : paths_sep = ';' ext = '.dll' libdir = basedir elif platform in ( 'linux' , 'linux2' ) : paths_sep = ':' ext = '.so'...
def pull_core ( self , ** kwargs ) : """Just the core of the pycurl logic ."""
str_ip = self . str_ip str_port = self . str_port verbose = 0 d_msg = { } for k , v in kwargs . items ( ) : if k == 'ip' : str_ip = v if k == 'port' : str_port = v if k == 'msg' : d_msg = v if k == 'verbose' : verbose = v response = io . BytesIO ( ) str_query = '' if len ...
def subscribe ( self , topic = b'' ) : """subscribe to the SUB socket , to listen for incomming variables , return a stream that can be listened to ."""
self . sockets [ zmq . SUB ] . setsockopt ( zmq . SUBSCRIBE , topic ) poller = self . pollers [ zmq . SUB ] return poller
def _parse_device_path ( self , device_path , char_path_override = None ) : """Parse each device and add to the approriate list ."""
# 1 . Make sure that we can parse the device path . try : device_type = device_path . rsplit ( '-' , 1 ) [ 1 ] except IndexError : warn ( "The following device path was skipped as it could " "not be parsed: %s" % device_path , RuntimeWarning ) return # 2 . Make sure each device is only added once . realpath...
def add_items ( self , dataframe , hide_cols = ( ) ) : """Add items and / or update existing items in grid"""
# replace " None " values with " " dataframe = dataframe . fillna ( "" ) # remove any columns that shouldn ' t be shown for col in hide_cols : if col in dataframe . columns : del dataframe [ col ] # add more rows self . AppendRows ( len ( dataframe ) ) columns = dataframe . columns row_num = - 1 # fill in a...
async def mget ( self , keys , * args ) : """Returns a list of values ordered identically to ` ` keys ` `"""
args = list_or_args ( keys , args ) return await self . execute_command ( 'MGET' , * args )
def normalize_file ( file , separators = None ) : """Normalizes the file path to use the POSIX path separator ( i . e . , ` ` ' / ' ` ` ) . * file * ( : class : ` str ` ) is the file path . * separators * ( : class : ` ~ collections . abc . Collection ` of : class : ` str ` ; or : data : ` None ` ) optionally...
# Normalize path separators . if separators is None : separators = NORMALIZE_PATH_SEPS norm_file = file for sep in separators : norm_file = norm_file . replace ( sep , posixpath . sep ) # Remove current directory prefix . if norm_file . startswith ( './' ) : norm_file = norm_file [ 2 : ] return norm_file
def getReqId ( self ) -> int : """Get new request ID ."""
if not self . isReady ( ) : raise ConnectionError ( 'Not connected' ) newId = self . _reqIdSeq self . _reqIdSeq += 1 return newId
def sub ( feednames ) : """Subscribe to the specified feed ( s ) ."""
ecode = 0 current_user_data = contexts . get ( 'anchore_auth' , { } ) . get ( 'user_info' , None ) if not current_user_data : current_user_tier = 0 else : current_user_tier = int ( current_user_data [ 'tier' ] ) try : for feed in feednames : rc , msg = anchore_feeds . subscribe_anchore_feed ( feed ,...
def from_KENT ( filepaths , name = None , ignore = [ "wm" ] , delay_tolerance = 0.1 , frequency_tolerance = 0.5 , parent = None , verbose = True , ) -> Data : """Create data object from KENT file ( s ) . Parameters filepaths : path - like or list of path - like Filepath ( s ) . Can be either a local or remo...
# define columns - - - - - # axes axes = collections . OrderedDict ( ) axes [ "w1" ] = { "units" : "wn" , "idx" : 0 , "label" : "1" } axes [ "w2" ] = { "units" : "wn" , "idx" : 1 , "label" : "2" } axes [ "wm" ] = { "units" : "wn" , "idx" : 2 , "label" : "m" } axes [ "d1" ] = { "units" : "ps" , "idx" : 3 , "label" : "1"...
def check_signature_supported ( func , warn = False ) : """Check if we support the signature of this function . We currently do not allow remote functions to have * * kwargs . We also do not support keyword arguments in conjunction with a * args argument . Args : func : The function whose signature should b...
function_name = func . __name__ sig_params = get_signature_params ( func ) has_kwargs_param = False has_kwonly_param = False for keyword_name , parameter in sig_params : if parameter . kind == Parameter . VAR_KEYWORD : has_kwargs_param = True if parameter . kind == Parameter . KEYWORD_ONLY : has...