signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def filter ( self , dates = None , min_dets = 1 ) : """Return a new Party filtered according to conditions . Return a new Party with only detections within a date range and only families with a minimum number of detections . : type dates : list of obspy . core . UTCDateTime objects : param dates : A start a...
if dates is None : raise MatchFilterError ( 'Need a list defining a date range' ) new_party = Party ( ) for fam in self . families : new_fam = Family ( template = fam . template , detections = [ det for det in fam if dates [ 0 ] < det . detect_time < dates [ 1 ] ] ) if len ( new_fam ) >= min_dets : ...
def load_iter ( self , key , chunksize = None , noexpire = None ) : '''Lookup an item in the cache and return an iterator that reads chunksize bytes of data at a time . The underlying file will be closed when all data has been read'''
return chunk_iterator ( self . load_fd ( key , noexpire = noexpire ) , chunksize = chunksize )
def set_leaf_dist ( self , attr_value , dist ) : """Sets the probability distribution at a leaf node ."""
assert self . attr_name assert self . tree . data . is_valid ( self . attr_name , attr_value ) , "Value %s is invalid for attribute %s." % ( attr_value , self . attr_name ) if self . is_continuous_class : assert isinstance ( dist , CDist ) assert self . attr_name self . _attr_value_cdist [ self . attr_name ...
def create_api_key ( name , description , enabled = True , stageKeys = None , region = None , key = None , keyid = None , profile = None ) : '''Create an API key given name and description . An optional enabled argument can be provided . If provided , the valid values are True | False . This argument defaults t...
try : stageKeys = list ( ) if stageKeys is None else stageKeys conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) response = conn . create_api_key ( name = name , description = description , enabled = enabled , stageKeys = stageKeys ) if not response : return { ...
def remove_from_known_hosts ( self , hosts , known_hosts = DEFAULT_KNOWN_HOSTS , dry = False ) : """Remove the remote host SSH public key to the ` known _ hosts ` file . : param hosts : the list of the remote ` Host ` objects . : param known _ hosts : the ` known _ hosts ` file to store the SSH public keys . ...
for host in hosts : logger . info ( '[%s] Removing the remote host SSH public key from [%s]...' , host . hostname , known_hosts ) cmd = [ 'ssh-keygen' , '-f' , known_hosts , '-R' , host . hostname ] logger . debug ( 'Call: %s' , ' ' . join ( cmd ) ) if not dry : try : subprocess . ch...
def has_element ( self , dat , skip_log = False ) : """: param dat : dict like { ' name ' : < the ele name > } : type dat : dict : param skip _ log : skip log at your wish : type skip _ log : : return : : rtype :"""
try : if self . get_elements ( dat , skip_log = skip_log ) : return True except Exception as _ : if not skip_log : log . error ( _ ) return False
def deserialize ( self , obj , encoders = None , embedded = False , create_instance = True ) : """Deserializes a given object , i . e . converts references to other ( known ) ` Document ` objects by lazy instances of the corresponding class . This allows the automatic fetching of related documents from the databa...
if not encoders : encoders = [ ] for encoder in encoders + self . standard_encoders : obj = encoder . decode ( obj ) if isinstance ( obj , dict ) : if create_instance and '__collection__' in obj and obj [ '__collection__' ] in self . collections and 'pk' in obj : # for backwards compatibility attrib...
def get_logs_from_db_reading ( job_prefix , reading_queue = 'run_db_reading_queue' ) : """Get the logs stashed on s3 for a particular reading ."""
s3 = boto3 . client ( 's3' ) gen_prefix = 'reading_results/%s/logs/%s' % ( job_prefix , reading_queue ) job_log_data = s3 . list_objects_v2 ( Bucket = 'bigmech' , Prefix = join ( gen_prefix , job_prefix ) ) # TODO : Track success / failure log_strs = [ ] for fdict in job_log_data [ 'Contents' ] : resp = s3 . get_ob...
def save_gradebook_column ( self , gradebook_column_form , * args , ** kwargs ) : """Pass through to provider GradebookColumnAdminSession . update _ gradebook _ column"""
# Implemented from kitosid template for - # osid . resource . ResourceAdminSession . update _ resource if gradebook_column_form . is_for_update ( ) : return self . update_gradebook_column ( gradebook_column_form , * args , ** kwargs ) else : return self . create_gradebook_column ( gradebook_column_form , * args...
def skip_item_key ( self , item , key ) : """Add the key to the item ' s " skip " list"""
if "skip" in item : item [ "skip" ] . append ( key ) else : item [ "skip" ] = [ key ] return item
def validateDatetime ( value , blank = False , strip = None , allowlistRegexes = None , blocklistRegexes = None , formats = ( '%Y/%m/%d %H:%M:%S' , '%y/%m/%d %H:%M:%S' , '%m/%d/%Y %H:%M:%S' , '%m/%d/%y %H:%M:%S' , '%x %H:%M:%S' , '%Y/%m/%d %H:%M' , '%y/%m/%d %H:%M' , '%m/%d/%Y %H:%M' , '%m/%d/%y %H:%M' , '%x %H:%M' , '...
# Reuse the logic in _ validateToDateTimeFormat ( ) for this function . try : return _validateToDateTimeFormat ( value , formats , blank = blank , strip = strip , allowlistRegexes = allowlistRegexes , blocklistRegexes = blocklistRegexes ) except ValidationException : _raiseValidationException ( _ ( '%r is not a...
def _selective_filter ( self , data , indices ) : """Selectively filter only pixels above ` ` filter _ threshold ` ` in the background mesh . The same pixels are filtered in both the background and background RMS meshes . Parameters data : 2D ` ~ numpy . ndarray ` A 2D array of mesh values . indices :...
data_out = np . copy ( data ) for i , j in zip ( * indices ) : yfs , xfs = self . filter_size hyfs , hxfs = yfs // 2 , xfs // 2 y0 , y1 = max ( i - hyfs , 0 ) , min ( i - hyfs + yfs , data . shape [ 0 ] ) x0 , x1 = max ( j - hxfs , 0 ) , min ( j - hxfs + xfs , data . shape [ 1 ] ) data_out [ i , j ]...
def response ( self , action = None ) : """returns cached response ( as dict ) for given action , or list of cached actions"""
if action in self . cache : return utils . json_loads ( self . cache [ action ] [ 'response' ] ) return self . cache . keys ( ) or None
def set_limits_for_pool ( self , pool , ** kw ) : """meterer . set _ limits _ for _ pool ( pool , [ time _ period = value ] ) Sets the limits for the given pool . The valid time _ periods are : year , month , week , day , hour ."""
pool_limits = { } for time_period in [ "year" , "month" , "week" , "day" , "hour" ] : if time_period not in kw : continue limit = kw . pop ( time_period ) if limit is not None and not isinstance ( limit , ( float , int ) ) : raise TypeError ( "%s must be a float or int or None" , time_period...
def get_egrc_config ( cli_egrc_path ) : """Return a Config namedtuple based on the contents of the egrc . If the egrc is not present , it returns an empty default Config . This method tries to use the egrc at cli _ egrc _ path , then the default path . cli _ egrc _ path : the path to the egrc as given on the ...
resolved_path = get_priority ( cli_egrc_path , DEFAULT_EGRC_PATH , None ) expanded_path = get_expanded_path ( resolved_path ) # Start as if nothing was defined in the egrc . egrc_config = get_empty_config ( ) if os . path . isfile ( expanded_path ) : egrc_config = get_config_tuple_from_egrc ( expanded_path ) return...
def args_update ( self ) : """Update the argparser namespace with any data from configuration file ."""
for key , value in self . _config_data . items ( ) : setattr ( self . _default_args , key , value )
def sum_ ( self , col : str ) -> float : """Returns the sum of all values in a column : param col : column name : type col : str : return : sum of all the column values : rtype : float : example : ` ` sum = ds . sum _ ( " Col 1 " ) ` `"""
try : df = self . df [ col ] num = float ( df . sum ( ) ) return num except Exception as e : self . err ( e , "Can not sum data on column " + str ( col ) )
def _set_pseudotime ( self ) : """Return pseudotime with respect to root point ."""
self . pseudotime = self . distances_dpt [ self . iroot ] . copy ( ) self . pseudotime /= np . max ( self . pseudotime [ self . pseudotime < np . inf ] )
def _segment ( cls , segment ) : """Returns a property capable of setting and getting a segment ."""
return property ( fget = lambda x : cls . _get_segment ( x , segment ) , fset = lambda x , v : cls . _set_segment ( x , segment , v ) , )
def _update_file_frontiers ( self , frontier_list , revision , max_csets_proc = 30 , going_forward = False ) : '''Update the frontier for all given files , up to the given revision . Built for quick continuous _ forward _ updating of large sets of files of TUIDs . Backward updating should be done through get ...
# Get the changelogs and revisions until we find the # last one we ' ve seen , and get the modified files in # each one . # Holds the files modified up to the last frontiers . files_to_process = { } # Holds all frontiers to find remaining_frontiers = { cset for cset in list ( set ( [ frontier for _ , frontier in fronti...
def _predict ( self , features ) : """Predict matches and non - matches . Parameters features : numpy . ndarray The data to predict the class of . Returns numpy . ndarray The predicted classes ."""
from sklearn . exceptions import NotFittedError try : prediction = self . kernel . predict_classes ( features ) [ : , 0 ] except NotFittedError : raise NotFittedError ( "{} is not fitted yet. Call 'fit' with appropriate " "arguments before using this method." . format ( type ( self ) . __name__ ) ) return predi...
def autocomplete ( input_list ) : """< Purpose > Returns all valid input completions for the specified command line input . < Arguments > input _ list : A list of tokens . < Side Effects > None < Exceptions > None < Returns > A list of strings representing valid completions ."""
# We are only interested if the last token starts with a single ' $ ' # Double $ $ ' s indicate that it is meant to be a ' $ ' , so we don ' t do anything . if input_list [ - 1 ] . startswith ( '$' ) and not input_list [ - 1 ] . startswith ( '$$' ) : # Omit the ' $ ' partial_variable = input_list [ - 1 ] [ 1 : ] ...
def create_session ( target = '' , timeout_sec = 10 ) : '''Create an intractive TensorFlow session . Helper function that creates TF session that uses growing GPU memory allocation and opration timeout . ' allow _ growth ' flag prevents TF from allocating the whole GPU memory an once , which is useful when ...
graph = tf . Graph ( ) config = tf . ConfigProto ( ) config . gpu_options . allow_growth = True config . operation_timeout_in_ms = int ( timeout_sec * 1000 ) return tf . InteractiveSession ( target = target , graph = graph , config = config )
def from_pyfile ( self , filename : str ) -> None : """Load values from a Python file ."""
globals_ = { } # type : Dict [ str , Any ] locals_ = { } # type : Dict [ str , Any ] with open ( filename , "rb" ) as f : exec ( compile ( f . read ( ) , filename , 'exec' ) , globals_ , locals_ ) for key , value in locals_ . items ( ) : if ( key . isupper ( ) and not isinstance ( value , types . ModuleType ) )...
def render_export_form ( self , request , context , form_url = '' ) : """Render the from submission export form ."""
context . update ( { 'has_change_permission' : self . has_change_permission ( request ) , 'form_url' : mark_safe ( form_url ) , 'opts' : self . opts , 'add' : True , 'save_on_top' : self . save_on_top , } ) return TemplateResponse ( request , self . export_form_template , context )
def __filename ( self , id ) : """Return the cache file name for an entry with a given id ."""
suffix = self . fnsuffix ( ) filename = "%s-%s.%s" % ( self . fnprefix , id , suffix ) return os . path . join ( self . location , filename )
def extract_indexes ( coords ) : """Yields the name & index of valid indexes from a mapping of coords"""
for name , variable in coords . items ( ) : variable = as_variable ( variable , name = name ) if variable . dims == ( name , ) : yield name , variable . to_index ( )
def dict_deep_merge ( tgt , src ) : """Utility function to merge the source dictionary ` src ` to the target dictionary recursively Note : The type of the values in the dictionary can only be ` dict ` or ` list ` Parameters : tgt ( dict ) : The target dictionary src ( dict ) : The source dictionary"""
for k , v in src . items ( ) : if k in tgt : if isinstance ( tgt [ k ] , dict ) and isinstance ( v , dict ) : dict_deep_merge ( tgt [ k ] , v ) else : tgt [ k ] . extend ( deepcopy ( v ) ) else : tgt [ k ] = deepcopy ( v )
def collectstatic ( settings_module , bin_env = None , no_post_process = False , ignore = None , dry_run = False , clear = False , link = False , no_default_ignore = False , pythonpath = None , env = None , runas = None ) : '''Collect static files from each of your applications into a single location that can eas...
args = [ 'noinput' ] kwargs = { } if no_post_process : args . append ( 'no-post-process' ) if ignore : kwargs [ 'ignore' ] = ignore if dry_run : args . append ( 'dry-run' ) if clear : args . append ( 'clear' ) if link : args . append ( 'link' ) if no_default_ignore : args . append ( 'no-default-...
def set_default_formatters ( self , which = None ) : """Sets the default formatters that is used for updating to None Parameters which : { None , ' minor ' , ' major ' } Specify which locator shall be set"""
if which is None or which == 'minor' : self . default_formatters [ 'minor' ] = self . axis . get_minor_formatter ( ) if which is None or which == 'major' : self . default_formatters [ 'major' ] = self . axis . get_major_formatter ( )
def new_event ( self , event_data : str ) -> None : """New event to process ."""
event = self . parse_event_xml ( event_data ) if EVENT_OPERATION in event : self . manage_event ( event )
def grab_bulbs ( host , token = None ) : """Grab XML , then add all bulbs to a dict . Removes room functionality"""
xml = grab_xml ( host , token ) bulbs = { } for room in xml : for device in room [ 'device' ] : bulbs [ int ( device [ 'did' ] ) ] = device return bulbs
def plot_vgp ( map_axis , vgp_lon = None , vgp_lat = None , di_block = None , label = '' , color = 'k' , marker = 'o' , edge = 'black' , markersize = 20 , legend = False ) : """This function plots a paleomagnetic pole position on a cartopy map axis . Before this function is called , a plot needs to be initialized...
if not has_cartopy : print ( '-W- cartopy must be installed to run ipmag.plot_vgp' ) return if di_block != None : di_lists = unpack_di_block ( di_block ) if len ( di_lists ) == 3 : vgp_lon , vgp_lat , intensity = di_lists if len ( di_lists ) == 2 : vgp_lon , vgp_lat = di_lists map_ax...
def inline_image ( image , mime_type = None , dst_color = None , src_color = None , spacing = None , collapse_x = None , collapse_y = None ) : """Embeds the contents of a file directly inside your stylesheet , eliminating the need for another HTTP request . For small files such images or fonts , this can be a p...
return _image_url ( image , False , False , dst_color , src_color , True , mime_type , spacing , collapse_x , collapse_y )
def filled_quantity ( self ) : """[ int ] 订单已成交数量"""
if np . isnan ( self . _filled_quantity ) : raise RuntimeError ( "Filled quantity of order {} is not supposed to be nan." . format ( self . order_id ) ) return self . _filled_quantity
def setSample ( self , sample ) : """Set sample points from the population . Should be a RDD"""
if not isinstance ( sample , RDD ) : raise TypeError ( "samples should be a RDD, received %s" % type ( sample ) ) self . _sample = sample
def init ( cls , conn_string = None ) : """Return the unique Meta class ."""
if conn_string : _update_meta ( conn_string ) # We initialize the engine within the models module because models ' # schema can depend on which data types are supported by the engine Meta . Session = new_sessionmaker ( ) Meta . engine = Meta . Session . kw [ "bind" ] logger . info ( f"Connecting...
def effstim ( self , fluxunits = 'photlam' ) : """Compute : ref : ` effective stimulus < pysynphot - formula - effstim > ` . Calculations are done in given flux unit , and wavelengths in Angstrom . Native dataset is used . Parameters fluxunits : str Flux unit . Returns ans : float Effective stimulus...
oldunits = self . fluxunits self . convert ( fluxunits ) x = units . Units ( fluxunits ) try : if x . isDensity : rate = self . integrate ( ) self . _fluxcheck ( rate ) if x . isMag : ans = x . unitResponse ( self . bandpass ) - 2.5 * math . log10 ( rate ) else : ...
def handle_message ( self , ch , method , properties , body ) : """this is a pika . basic _ consumer callback handles client inputs , runs appropriate workflows and views Args : ch : amqp channel method : amqp method properties : body : message body"""
input = { } headers = { } try : self . sessid = method . routing_key input = json_decode ( body ) data = input [ 'data' ] # since this comes as " path " we dont know if it ' s view or workflow yet # TODO : just a workaround till we modify ui to if 'path' in data : if data [ 'path' ] in V...
def get_appliance ( self , id_or_uri , fields = '' ) : """Gets the particular Image Streamer resource based on its ID or URI . Args : id _ or _ uri : Can be either the Os Deployment Server ID or the URI fields : Specifies which fields should be returned in the result . Returns : dict : Image Streamer ...
uri = self . URI + '/image-streamer-appliances/' + extract_id_from_uri ( id_or_uri ) if fields : uri += '?fields=' + fields return self . _client . get ( uri )
def validation_statuses ( self , area_uuid ) : """Get count of validation statuses for all files in upload _ area : param str area _ uuid : A RFC4122 - compliant ID for the upload area : return : a dict with key for each state and value being the count of files in that state : rtype : dict : raises UploadAp...
path = "/area/{uuid}/validations" . format ( uuid = area_uuid ) result = self . _make_request ( 'get' , path ) return result . json ( )
def different_forks ( self , lnode , rnode ) : """True , if lnode and rnode are located on different forks of IF / TRY ."""
ancestor = self . get_common_ancestor ( lnode , rnode ) if isinstance ( ancestor , ast . If ) : for fork in ( ancestor . body , ancestor . orelse ) : if self . on_fork ( ancestor , lnode , rnode , fork ) : return True elif isinstance ( ancestor , ast . Try ) : body = ancestor . body + ancest...
def rowCount ( self , index = None ) : """Get number of rows in the header ."""
if self . axis == 0 : return max ( 1 , self . _shape [ 0 ] ) else : if self . total_rows <= self . rows_loaded : return self . total_rows else : return self . rows_loaded
def GetAnalysisStatusUpdateCallback ( self ) : """Retrieves the analysis status update callback function . Returns : function : status update callback function or None if not available ."""
if self . _mode == self . MODE_LINEAR : return self . _PrintAnalysisStatusUpdateLinear if self . _mode == self . MODE_WINDOW : return self . _PrintAnalysisStatusUpdateWindow return None
def is_alive ( self , container : Container ) -> bool : """Determines whether or not a given container is still alive ."""
uid = container . uid r = self . __api . get ( 'containers/{}/alive' . format ( uid ) ) if r . status_code == 200 : return r . json ( ) if r . status_code == 404 : raise KeyError ( "no container found with given UID: {}" . format ( uid ) ) self . __api . handle_erroneous_response ( r )
def update_positions ( tree , positions ) : """Updates the tree with new positions"""
for step , pos in zip ( tree . findall ( 'step' ) , positions ) : for key in sorted ( pos ) : value = pos . get ( key ) if key . endswith ( "-rel" ) : abs_key = key [ : key . index ( "-rel" ) ] if value is not None : els = tree . findall ( ".//*[@id='" + value...
def _getLayer ( self , name , ** kwargs ) : """This is the environment implementation of : meth : ` BaseFont . getLayer ` . * * name * * will be a : ref : ` type - string ` . It will have been normalized with : func : ` normalizers . normalizeLayerName ` and it will have been verified as an existing layer ....
for layer in self . layers : if layer . name == name : return layer
def connection_end ( self , value ) : """Setter for * * self . _ _ connection _ end * * attribute . : param value : Attribute value . : type value : unicode"""
if value is not None : assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "connection_end" , value ) self . __connection_end = value
def sources_add ( name , ruby = None , user = None ) : '''Make sure that a gem source is added . name The URL of the gem source to be added ruby : None For RVM or rbenv installations : the ruby version and gemset to target . user : None The user under which to run the ` ` gem ` ` command . . versionad...
ret = { 'name' : name , 'result' : None , 'comment' : '' , 'changes' : { } } if name in __salt__ [ 'gem.sources_list' ] ( ruby , runas = user ) : ret [ 'result' ] = True ret [ 'comment' ] = 'Gem source is already added.' return ret if __opts__ [ 'test' ] : ret [ 'comment' ] = 'The gem source {0} would h...
def delete_object ( self , identifier , erase = False ) : """Delete the entry with given identifier in the database . Returns the handle for the deleted object or None if object identifier is unknown . If the read - only property of the object is set to true a ValueError is raised . Parameters identifier ...
# Get object to ensure that it exists . db_object = self . get_object ( identifier ) # Set active flag to False if object exists . if db_object is None : return None # Check whether the read - only property is set to true if PROPERTY_READONLY in db_object . properties : if db_object . properties [ PROPERTY_READ...
def update_selected ( self , other , selected ) : """Like update , however a list of selected keys must be provided ."""
self . update ( { k : other [ k ] for k in selected } )
def parse_data_port_mappings ( mappings , default_bridge = 'br-data' ) : """Parse data port mappings . Mappings must be a space - delimited list of bridge : port . Returns dict of the form { port : bridge } where ports may be mac addresses or interface names ."""
# NOTE ( dosaboy ) : we use rvalue for key to allow multiple values to be # proposed for < port > since it may be a mac address which will differ # across units this allowing first - known - good to be chosen . _mappings = parse_mappings ( mappings , key_rvalue = True ) if not _mappings or list ( _mappings . values ( )...
def generate_method_definition ( func ) : """Generates the body for the given function : param dict func : dict of a JSON - Formatted function as defined by the API docs : return : A String containing the definition for the function as it should be written in code : rtype : str"""
indent = 4 # initial definition method_definition = ( " " * indent ) + "def " + func [ "name" ] # Here we just create a queue and put all the parameters # into the queue in the order that they were given , params_required = [ param for param in func [ "arguments" ] if param [ "is_required" ] ] params_optional = [ param...
def get_block_details ( self , block_ids ) : """Get details of scheduling or processing block Args : block _ ids ( list ) : List of block IDs"""
# Convert input to list if needed if not hasattr ( block_ids , "__iter__" ) : block_ids = [ block_ids ] for _id in block_ids : block_key = self . _db . get_block ( _id ) [ 0 ] block_data = self . _db . get_all_field_value ( block_key ) # NOTE ( BM ) unfortunately this doesn ' t quite work for keys where...
def _check_transition_id ( self , transition ) : """Checks the validity of a transition id Checks whether the transition id is already used by another transition within the state : param rafcon . core . transition . Transition transition : The transition to be checked : return bool validity , str message : va...
transition_id = transition . transition_id if transition_id in self . transitions and transition is not self . transitions [ transition_id ] : return False , "transition_id already existing" return True , "valid"
def _make_xml_files ( catalog_info_dict , comp_info_dict ) : """Make all the xml file for individual components"""
for val in catalog_info_dict . values ( ) : val . roi_model . write_xml ( val . srcmdl_name ) for val in comp_info_dict . values ( ) : for val2 in val . values ( ) : val2 . roi_model . write_xml ( val2 . srcmdl_name )
def set_max_order_size ( self , asset = None , max_shares = None , max_notional = None , on_error = 'fail' ) : """Set a limit on the number of shares and / or dollar value of any single order placed for sid . Limits are treated as absolute values and are enforced at the time that the algo attempts to place an o...
control = MaxOrderSize ( asset = asset , max_shares = max_shares , max_notional = max_notional , on_error = on_error ) self . register_trading_control ( control )
def score ( self , data , metric = "accuracy" , validation_task = None , reduce = "mean" , break_ties = "random" , verbose = True , print_confusion_matrix = False , ** kwargs , ) : """Scores the predictive performance of the Classifier on all tasks Args : data : either a Pytorch Dataset , DataLoader or tuple su...
Y_p , Y , Y_s = self . _get_predictions ( data , break_ties = break_ties , return_probs = True , ** kwargs ) # TODO : Handle multiple metrics . . . metric_list = metric if isinstance ( metric , list ) else [ metric ] if len ( metric_list ) > 1 : raise NotImplementedError ( "Multiple metrics for multi-task score() n...
def get_vgg ( num_layers , pretrained = False , ctx = cpu ( ) , root = os . path . join ( base . data_dir ( ) , 'models' ) , ** kwargs ) : r"""VGG model from the ` " Very Deep Convolutional Networks for Large - Scale Image Recognition " < https : / / arxiv . org / abs / 1409.1556 > ` _ paper . Parameters num ...
layers , filters = vgg_spec [ num_layers ] net = VGG ( layers , filters , ** kwargs ) if pretrained : from . . model_store import get_model_file batch_norm_suffix = '_bn' if kwargs . get ( 'batch_norm' ) else '' net . load_parameters ( get_model_file ( 'vgg%d%s' % ( num_layers , batch_norm_suffix ) , root =...
def _init_evals_bps ( self , evals , breakpoints ) : # If an eval or bp is the tf . Placeholder output of a tdb . PythonOp , replace it with its respective PythonOp node evals2 = [ op_store . get_op ( t ) if op_store . is_htop_out ( t ) else t for t in evals ] breakpoints2 = [ op_store . get_op ( t ) if op_stor...
self . _evalset = set ( [ e . name for e in evals2 ] ) for e in self . _exe_order : if isinstance ( e , HTOp ) : self . _evalset . add ( e . name ) for t in e . inputs : if not op_store . is_htop_out ( t ) : self . _evalset . add ( t . name ) # compute breakpoint set self...
def get_geometries ( self , coordination = None , returned = 'cg' ) : """Returns a list of coordination geometries with the given coordination number . : param coordination : The coordination number of which the list of coordination geometries are returned ."""
geom = list ( ) if coordination is None : for gg in self . cg_list : if returned == 'cg' : geom . append ( gg ) elif returned == 'mp_symbol' : geom . append ( gg . mp_symbol ) else : for gg in self . cg_list : if gg . get_coordination_number ( ) == coordination : ...
def df_to_dat ( net , df , define_cat_colors = False ) : '''This is always run when data is loaded .'''
from . import categories # check if df has unique values df [ 'mat' ] = make_unique_labels . main ( net , df [ 'mat' ] ) net . dat [ 'mat' ] = df [ 'mat' ] . values net . dat [ 'nodes' ] [ 'row' ] = df [ 'mat' ] . index . tolist ( ) net . dat [ 'nodes' ] [ 'col' ] = df [ 'mat' ] . columns . tolist ( ) for inst_rc in [ ...
def nose_selector ( test ) : """Return the string you can pass to nose to run ` test ` , including argument values if the test was made by a test generator . Return " Unknown test " if it can ' t construct a decent path ."""
address = test_address ( test ) if address : file , module , rest = address if module : if rest : try : return '%s:%s%s' % ( module , rest , test . test . arg or '' ) except AttributeError : return '%s:%s' % ( module , rest ) else : ...
def parse_datetime ( datetimestring ) : '''Parses ISO 8601 date - times into datetime . datetime objects . This function uses parse _ date and parse _ time to do the job , so it allows more combinations of date and time representations , than the actual ISO 8601:2004 standard allows .'''
try : datestring , timestring = re . split ( 'T| ' , datetimestring ) except ValueError : raise isodate . ISO8601Error ( "ISO 8601 time designator 'T' or ' ' missing. Unable to parse " "datetime string %r" % datetimestring ) tmpdate = isodate . parse_date ( datestring ) tmptime = isodate . parse_time ( timestr...
def persist ( self , storageLevel ) : """Persist the RDDs of this DStream with the given storage level"""
self . is_cached = True javaStorageLevel = self . _sc . _getJavaStorageLevel ( storageLevel ) self . _jdstream . persist ( javaStorageLevel ) return self
def rename_collection ( db , collection , new_name ) : '''Renames a MongoDB collection . Arguments : db ( Database ) : A pymongo Database object . Can be obtained with ` ` get _ db ` ` . collection ( str ) : Name of the collection to be renamed . new _ name ( str , func ) : ` ` new _ name ` ` can be one o...
if hasattr ( new_name , '__call__' ) : _new = new_name ( collection ) if _new == '' : return else : _new = new_name c = db [ collection ] c . rename ( _new )
def update ( self , dt = - 1 ) : """Return type string , compatible with numpy ."""
self . library . update . argtypes = [ c_double ] self . library . update . restype = c_int if dt == - 1 : # use default timestep dt = self . get_time_step ( ) result = wrap ( self . library . update ) ( dt ) return result
def parse_code_ul ( self , url , ul ) : """Fill the toc item"""
li_list = ul . find_all ( 'li' , recursive = False ) li = li_list [ 0 ] span_title = li . find ( 'span' , attrs = { 'class' : re . compile ( r'TM\d+Code' ) } , recursive = False ) section = Section ( span_title . attrs [ 'id' ] , span_title . text . strip ( ) ) div_italic = li . find ( 'div' , attrs = { 'class' : 'ital...
def _createShapelet ( self , coeff ) : """returns a shapelet array out of the coefficients * a , up to order l : param num _ l : order of shapelets : type num _ l : int . : param coeff : shapelet coefficients : type coeff : floats : returns : complex array : raises : AttributeError , KeyError"""
n_coeffs = len ( coeff ) num_l = self . _get_num_l ( n_coeffs ) shapelets = np . zeros ( ( num_l + 1 , num_l + 1 ) , 'complex' ) nl = 0 k = 0 i = 0 while i < len ( coeff ) : if i % 2 == 0 : shapelets [ nl ] [ k ] += coeff [ i ] / 2. shapelets [ k ] [ nl ] += coeff [ i ] / 2. if k == nl : ...
def error ( self , instance , value , error_class = None , extra = '' ) : """Generates a ValueError on setting property to an invalid value"""
error_class = error_class or ValidationError if not isinstance ( value , ( list , tuple , np . ndarray ) ) : super ( Array , self ) . error ( instance , value , error_class , extra ) if isinstance ( value , ( list , tuple ) ) : val_description = 'A {typ} of length {len}' . format ( typ = value . __class__ . __n...
def update_if_client ( fctn ) : """Intercept and check updates from server if bundle is in client mode ."""
@ functools . wraps ( fctn ) def _update_if_client ( self , * args , ** kwargs ) : b = self . _bundle if b is None or not hasattr ( b , 'is_client' ) : return fctn ( self , * args , ** kwargs ) elif b . is_client and ( b . _last_client_update is None or ( datetime . now ( ) - b . _last_client_update...
def fib ( n ) : """Terrible Fibonacci number generator ."""
v = n . value return v if v < 2 else fib2 ( PythonInt ( v - 1 ) ) + fib ( PythonInt ( v - 2 ) )
def wizard_font ( text ) : """Check input text length for wizard mode . : param text : input text : type text : str : return : font as str"""
text_length = len ( text ) if text_length <= TEXT_XLARGE_THRESHOLD : font = random . choice ( XLARGE_WIZARD_FONT ) elif text_length > TEXT_XLARGE_THRESHOLD and text_length <= TEXT_LARGE_THRESHOLD : font = random . choice ( LARGE_WIZARD_FONT ) elif text_length > TEXT_LARGE_THRESHOLD and text_length <= TEXT_MEDIU...
def add_scope_ip ( hostipaddress , name , description , auth , url , scopeid = None , network_address = None ) : """Function to add new host IP address allocation to existing scope ID : param hostipaddress : ipv4 address of the target host to be added to the target scope : param name : name of the owner of this...
if network_address is not None : scopeid = get_scope_id ( network_address , auth , url ) if scopeid == "Scope Doesn't Exist" : return scopeid new_ip = { "ip" : hostipaddress , "name" : name , "description" : description } f_url = url + '/imcrs/res/access/assignedIpScope/ip?ipScopeId=' + str ( scopeid ) ...
def fix_scheme ( url ) : '''Prepends the http : / / scheme if necessary to a url . Fails if a scheme other than http is used'''
splitted = url . split ( '://' ) if len ( splitted ) == 2 : if splitted [ 0 ] in ( 'http' , 'https' ) : return url else : raise exc . WileECoyoteException ( 'Bad scheme! Got: {}, expected http or https' . format ( splitted [ 0 ] ) ) elif len ( splitted ) == 1 : return 'http://' + url else : ...
def update_environmental_configuration ( self , configuration , timeout = - 1 ) : """Sets the calibrated max power of an unmanaged or unsupported enclosure . Args : configuration : Configuration timeout : Timeout in seconds . Wait for task completion by default . The timeout does not abort the operation in ...
uri = '{}/environmentalConfiguration' . format ( self . data [ 'uri' ] ) return self . _helper . do_put ( uri , configuration , timeout , None )
def _time_to_minutes ( self , time_str ) : """Convert a time string to the equivalent number in minutes as an int . Return 0 if the time _ str is not a valid amount of time . > > > jump = JumprunProApi ( ' skydive - warren - county ' ) > > > jump . _ time _ to _ minutes ( ' 34 minutes ' ) 34 > > > jump . ...
minutes = 0 try : call_time_obj = parser . parse ( time_str ) minutes = call_time_obj . minute minutes += call_time_obj . hour * 60 except ValueError : minutes = 0 return minutes
def set_data ( self , xs = None , ys = None , zs = None , colors = None ) : '''Update the mesh data . Parameters xs : ndarray | None A 2d array of x coordinates for the vertices of the mesh . ys : ndarray | None A 2d array of y coordinates for the vertices of the mesh . zs : ndarray | None A 2d array ...
if xs is None : xs = self . _xs self . __vertices = None if ys is None : ys = self . _ys self . __vertices = None if zs is None : zs = self . _zs self . __vertices = None if self . __vertices is None : vertices , indices = create_grid_mesh ( xs , ys , zs ) self . _xs = xs self . _ys ...
def access_list ( package ) : """Print list of users who can access a package ."""
team , owner , pkg = parse_package ( package ) session = _get_session ( team ) lookup_url = "{url}/api/access/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) response = session . get ( lookup_url ) data = response . json ( ) users = data [ 'users' ] print ( '\n' . join ( users )...
def save_context ( context ) : """Save a Context object to user data directory ."""
file_path = _get_context_filepath ( ) content = format_to_http_prompt ( context , excluded_options = EXCLUDED_OPTIONS ) with io . open ( file_path , 'w' , encoding = 'utf-8' ) as f : f . write ( content )
def synthesize ( self , duration , tick_frequency ) : """Synthesize periodic " ticks " , generated from white noise and an envelope Args : duration ( numpy . timedelta64 ) : The total duration of the sound to be synthesized tick _ frequency ( numpy . timedelta64 ) : The frequency of the ticking sound"""
sr = self . samplerate . samples_per_second # create a short , tick sound tick = np . random . uniform ( low = - 1. , high = 1. , size = int ( sr * .1 ) ) tick *= np . linspace ( 1 , 0 , len ( tick ) ) # create silence samples = np . zeros ( int ( sr * ( duration / Seconds ( 1 ) ) ) ) ticks_per_second = Seconds ( 1 ) /...
def parse ( self , file_name ) : """Parse entire file and return relevant object . : param file _ name : File path : type file _ name : str : return : Parsed object"""
self . object = self . parsed_class ( ) with open ( file_name , encoding = 'utf-8' ) as f : self . parse_str ( f . read ( ) ) return self . object
def ApertureHDU ( model ) : '''Construct the HDU containing the aperture used to de - trend .'''
# Get mission cards cards = model . _mission . HDUCards ( model . meta , hdu = 3 ) # Add EVEREST info cards . append ( ( 'COMMENT' , '************************' ) ) cards . append ( ( 'COMMENT' , '* EVEREST INFO *' ) ) cards . append ( ( 'COMMENT' , '************************' ) ) cards . append ( ( 'MISSION' , m...
def sshAppliance ( self , * args , ** kwargs ) : """: param args : arguments to execute in the appliance : param kwargs : tty = bool tells docker whether or not to create a TTY shell for interactive SSHing . The default value is False . Input = string is passed as input to the Popen call ."""
kwargs [ 'appliance' ] = True return self . coreSSH ( * args , ** kwargs )
def Setup ( self ) : """Initialize the local node . Returns :"""
self . Peers = [ ] # active nodes that we ' re connected to self . KNOWN_ADDRS = [ ] # node addresses that we ' ve learned about from other nodes self . DEAD_ADDRS = [ ] # addresses that were performing poorly or we could not establish a connection to self . MissionsGlobal = [ ] self . NodeId = random . randint ( 12949...
def from_global_id ( global_id ) : '''Takes the " global ID " created by toGlobalID , and retuns the type name and ID used to create it .'''
unbased_global_id = unbase64 ( global_id ) _type , _id = unbased_global_id . split ( ':' , 1 ) return _type , _id
def zremrangebyscore ( self , key , min_score , max_score ) : """Removes all elements in the sorted set stored at key with a score between min and max . Intervals are described in : meth : ` ~ tredis . RedisClient . zrangebyscore ` . Returns the number of elements removed . . . note : : * * Time complexit...
return self . _execute ( [ b'ZREMRANGEBYSCORE' , key , min_score , max_score ] )
async def get_entity ( self ) : """Returns ` entity ` but will make an API call if necessary ."""
if not self . entity and await self . get_input_entity ( ) : try : self . _entity = await self . _client . get_entity ( self . _input_entity ) except ValueError : pass return self . _entity
def properties ( obj ) : """Returns a dictionary with one entry per attribute of the given object . The key being the attribute name and the value being the attribute value . Attributes starting in two underscores will be ignored . This function is an alternative to vars ( ) which only returns instance variab...
return dict ( ( attr , getattr ( obj , attr ) ) for attr in dir ( obj ) if not attr . startswith ( '__' ) )
def popError ( text , title = "Lackey Error" ) : """Creates an error dialog with the specified text ."""
root = tk . Tk ( ) root . withdraw ( ) tkMessageBox . showerror ( title , text )
def get_default_cache ( ) : """Get the default cache location . Adheres to the XDG Base Directory specification , as described in https : / / standards . freedesktop . org / basedir - spec / basedir - spec - latest . html : return : the default cache directory absolute path"""
xdg_cache_home = os . environ . get ( 'XDG_CACHE_HOME' ) or os . path . join ( os . path . expanduser ( '~' ) , '.cache' ) return os . path . join ( xdg_cache_home , 'pokebase' )
def handle_job_and_work_delete ( self , sender , instance , ** kwargs ) : """Custom handler for job and work delete"""
self . handle_delete ( instance . project . __class__ , instance . project )
def valid ( a , b ) : """Check whether ` a ` and ` b ` are not inf or nan"""
return ~ ( np . isnan ( a ) | np . isinf ( a ) | np . isnan ( b ) | np . isinf ( b ) )
def transmit ( self , bytes , protocol = None ) : """Cypher / uncypher APDUs before transmission"""
cypheredbytes = self . cypher ( bytes ) data , sw1 , sw2 = CardConnectionDecorator . transmit ( self , cypheredbytes , protocol ) if [ ] != data : data = self . uncypher ( data ) return data , sw1 , sw2
def db_getHex ( self , db_name , key ) : """https : / / github . com / ethereum / wiki / wiki / JSON - RPC # db _ gethex DEPRECATED"""
warnings . warn ( 'deprecated' , DeprecationWarning ) return ( yield from self . rpc_call ( 'db_getHex' , [ db_name , key ] ) )
def _is_installation_local ( name ) : """Check whether the distribution is in the current Python installation . This is used to distinguish packages seen by a virtual environment . A venv may be able to see global packages , but we don ' t want to mess with them ."""
loc = os . path . normcase ( pkg_resources . working_set . by_key [ name ] . location ) pre = os . path . normcase ( sys . prefix ) return os . path . commonprefix ( [ loc , pre ] ) == pre
def run ( self ) : """Executed on startup of application"""
for wsock in self . wsocks : wsock . run ( ) for api in self . apis : api . run ( )
def _finalize_merge ( out_file , bam_files , config ) : """Handle indexes and cleanups of merged BAM and input files ."""
# Ensure timestamps are up to date on output file and index # Works around issues on systems with inconsistent times for ext in [ "" , ".bai" ] : if os . path . exists ( out_file + ext ) : subprocess . check_call ( [ "touch" , out_file + ext ] ) for b in bam_files : utils . save_diskspace ( b , "BAM mer...
def _FindKeys ( self , key , names , matches ) : """Searches the plist key hierarchy for keys with matching names . If a match is found a tuple of the key name and value is added to the matches list . Args : key ( dict [ str , object ] ) : plist key . names ( list [ str ] ) : names of the keys to match . ...
for name , subkey in iter ( key . items ( ) ) : if name in names : matches . append ( ( name , subkey ) ) if isinstance ( subkey , dict ) : self . _FindKeys ( subkey , names , matches )
def create_snapshot ( self , name , tag ) : """Create new instance of image with snaphot image ( it is copied inside class constructuor ) : param name : str - name of image - not used now : param tag : str - tag for image : return : NspawnImage instance"""
source = self . local_location logger . debug ( "Create Snapshot: %s -> %s" % ( source , name ) ) # FIXME : actually create the snapshot via clone command if name and tag : output_tag = "{}:{}" . format ( name , tag ) else : output_tag = name or tag return self . __class__ ( repository = source , tag = output_t...