signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def read_dev_prop ( self , device_name ) : """Device properties retrieved from pickle"""
with open ( "{}.bin" . format ( device_name ) , "rb" ) as file : return pickle . load ( file ) [ "device" ]
def prepare_destruction ( self ) : """Prepares the model for destruction Unregister itself as observer from the state machine and the root state"""
if self . state_machine is None : logger . verbose ( "Multiple calls of prepare destruction for {0}" . format ( self ) ) self . destruction_signal . emit ( ) if self . history is not None : self . history . prepare_destruction ( ) if self . auto_backup is not None : self . auto_backup . prepare_destruction ...
def densify ( self , geometries , sr , maxSegmentLength , lengthUnit , geodesic = False , ) : """The densify operation is performed on a geometry service resource . This operation densifies geometries by plotting points between existing vertices . Inputs : geometries - array of geometries to be densified ( st...
url = self . _url + "/densify" params = { "f" : "json" , "sr" : sr , "maxSegmentLength" : maxSegmentLength , "lengthUnit" : lengthUnit , "geodesic" : geodesic } if isinstance ( geometries , list ) and len ( geometries ) > 0 : template = { "geometryType" : None , "geometries" : [ ] } for g in geometries : ...
def with_base_config ( base_config , extra_config ) : """Returns the given config dict merged with a base agent conf ."""
config = copy . deepcopy ( base_config ) config . update ( extra_config ) return config
def filter_lines ( input_file , output_file , translate = lambda line : line ) : """Translate all the lines of a single file"""
filepath , lines = get_lines ( [ input_file ] ) [ 0 ] return filepath , [ ( tag , translate ( line = line , tag = tag ) ) for ( tag , line ) in lines ]
def update ( anchor , handle = None ) : """Update an anchor based on the current contents of its source file . Args : anchor : The ` Anchor ` to be updated . handle : File - like object containing contents of the anchor ' s file . If ` None ` , then this function will open the file and read it . Returns :...
if handle is None : with anchor . file_path . open ( mode = 'rt' ) as fp : source_text = fp . read ( ) else : source_text = handle . read ( ) handle . seek ( 0 ) ctxt = anchor . context a_score , alignments = align ( ctxt . full_text , source_text , score , gap_penalty ) # max _ score = len ( ctxt ....
def new_transfer_transaction ( self , asset : str , b58_from_address : str , b58_to_address : str , amount : int , b58_payer_address : str , gas_limit : int , gas_price : int ) -> Transaction : """This interface is used to generate a Transaction object for transfer . : param asset : a string which is used to indi...
if not isinstance ( b58_from_address , str ) or not isinstance ( b58_to_address , str ) or not isinstance ( b58_payer_address , str ) : raise SDKException ( ErrorCode . param_err ( 'the data type of base58 encode address should be the string.' ) ) if len ( b58_from_address ) != 34 or len ( b58_to_address ) != 34 or...
def fetch_and_process_data ( self , collection , pipeline ) : """Fetches and Processess data from the input collection by aggregating using the pipeline : param collection : The collection object for which mongo connection has to be made : type collection : MongoCollection : param pipeline : The pipeline usin...
collection_cursor = collection . get_mongo_cursor ( ) grouped_docs = list ( collection_cursor . aggregate ( pipeline ) ) grouped_docs_dict = { } while grouped_docs : doc = grouped_docs . pop ( ) keys_list = [ ] for group_by_key in self . join_keys : keys_list . append ( doc [ "_id" ] . get ( group_b...
def get_adjacent_pathways ( self , pathway ) : """Get the pathways adjacent to this pathway in the network Parameters pathway : str Returns list ( str ) , a list of pathways adjacent to the input pathway"""
vertex_id = self . pathways [ pathway ] adjacent = self . vertices [ vertex_id ] . get_adjacent_vertex_ids ( ) adjacent_pathways = [ ] for adjacent_id in adjacent : adjacent_pathways . append ( self . get_pathway_from_vertex_id ( adjacent_id ) ) return adjacent_pathways
def _find_usage_route_tables ( self ) : """find usage for route tables"""
# Route tables per VPC tables = defaultdict ( int ) for table in self . conn . describe_route_tables ( ) [ 'RouteTables' ] : tables [ table [ 'VpcId' ] ] += 1 # Entries per route table routes = [ r for r in table [ 'Routes' ] if r [ 'Origin' ] != 'EnableVgwRoutePropagation' ] self . limits [ 'Entries pe...
def components ( self ) : """Extract connected components from graph . Useful for ensuring that you ' re working with a single tree . Returns : [ PrecomputedSkeleton , PrecomputedSkeleton , . . . ]"""
skel , forest = self . _compute_components ( ) if len ( forest ) == 0 : return [ ] elif len ( forest ) == 1 : return [ skel ] orig_verts = { tuple ( coord ) : i for i , coord in enumerate ( skel . vertices ) } skeletons = [ ] for edge_list in forest : edge_list = np . array ( edge_list , dtype = np . uint32...
def add_filter ( self , property_name , operator , value ) : """Filter the query based on a property name , operator and a value . Expressions take the form of : : . add _ filter ( ' < property > ' , ' < operator > ' , < value > ) where property is a property stored on the entity in the datastore and operat...
if self . OPERATORS . get ( operator ) is None : error_message = 'Invalid expression: "%s"' % ( operator , ) choices_message = "Please use one of: =, <, <=, >, >=." raise ValueError ( error_message , choices_message ) if property_name == "__key__" and not isinstance ( value , Key ) : raise ValueError ( ...
def _start_update_server ( auth_token ) : """Start a TCP server to receive accumulator updates in a daemon thread , and returns it"""
server = AccumulatorServer ( ( "localhost" , 0 ) , _UpdateRequestHandler , auth_token ) thread = threading . Thread ( target = server . serve_forever ) thread . daemon = True thread . start ( ) return server
def get_accuracy ( targets , outputs , k = 1 , ignore_index = None ) : """Get the accuracy top - k accuracy between two tensors . Args : targets ( 1 - 2D : class : ` torch . Tensor ` ) : Target or true vector against which to measure saccuracy outputs ( 1 - 3D : class : ` torch . Tensor ` ) : Prediction or ...
n_correct = 0.0 for target , output in zip ( targets , outputs ) : if not torch . is_tensor ( target ) or is_scalar ( target ) : target = torch . LongTensor ( [ target ] ) if not torch . is_tensor ( output ) or is_scalar ( output ) : output = torch . LongTensor ( [ [ output ] ] ) predictions...
def _add_gmaf ( self , variant_obj , gemini_variant ) : """Add the gmaf frequency Args : variant _ obj ( puzzle . models . Variant ) gemini _ variant ( GeminiQueryRow )"""
max_af = gemini_variant [ 'max_aaf_all' ] if max_af : max_af = float ( max_af ) if max_af != - 1.0 : variant_obj . set_max_freq ( max_af )
def encrypt ( self , message , public_key ) : """Encrypts a string using a given rsa . PublicKey object . If the message is larger than the key , it will split it up into a list and encrypt each line in the list . Args : message ( string ) : The string to encrypt . public _ key ( rsa . PublicKey ) : The k...
# Get the maximum message length based on the key max_str_len = rsa . common . byte_size ( public_key . n ) - 11 # If the message is longer than the key size , split it into a list to # be encrypted if len ( message ) > max_str_len : message = textwrap . wrap ( message , width = max_str_len ) else : message = [...
def get ( self , request , pzone_pk ) : """Get all the operations for a given pzone ."""
# attempt to get given pzone try : pzone = PZone . objects . get ( pk = pzone_pk ) except PZone . DoesNotExist : raise Http404 ( "Cannot find given pzone." ) # bulid filters filters = { "pzone" : pzone } if "from" in request . GET : parsed = dateparse . parse_datetime ( request . GET [ "from" ] ) if par...
def slim_stem ( token ) : """A very simple stemmer , for entity of GO stemming . > > > token = ' interaction ' > > > slim _ stem ( token ) ' interact '"""
target_sulfixs = [ 'ic' , 'tic' , 'e' , 'ive' , 'ing' , 'ical' , 'nal' , 'al' , 'ism' , 'ion' , 'ation' , 'ar' , 'sis' , 'us' , 'ment' ] for sulfix in sorted ( target_sulfixs , key = len , reverse = True ) : if token . endswith ( sulfix ) : token = token [ 0 : - len ( sulfix ) ] break if token . end...
def _calc_entropy ( data , size = None ) : """Calculate the entropy of a piece of data : param data : The target data to calculate entropy on : param size : Size of the data , Optional . : return : A float"""
if not data : return 0 entropy = 0 if size is None : size = len ( data ) data = bytes ( pyvex . ffi . buffer ( data , size ) ) for x in range ( 0 , 256 ) : p_x = float ( data . count ( x ) ) / size if p_x > 0 : entropy += - p_x * math . log ( p_x , 2 ) return entropy
def spline ( points , smooth = 0.5 , degree = 2 , s = 2 , c = "b" , alpha = 1.0 , nodes = False , res = 20 ) : """Return an ` ` Actor ` ` for a spline so that it does not necessarly pass exactly throught all points . : param float smooth : smoothing factor . 0 = interpolate points exactly . 1 = average point posi...
from scipy . interpolate import splprep , splev Nout = len ( points ) * res # Number of points on the spline points = np . array ( points ) minx , miny , minz = np . min ( points , axis = 0 ) maxx , maxy , maxz = np . max ( points , axis = 0 ) maxb = max ( maxx - minx , maxy - miny , maxz - minz ) smooth *= maxb / 2 # ...
def start_with ( self , x ) : """Returns all arguments beginning with given string ( or list thereof ) ."""
_args = [ ] for arg in self . all : if _is_collection ( x ) : for _x in x : if arg . startswith ( x ) : _args . append ( arg ) break else : if arg . startswith ( x ) : _args . append ( arg ) return ArgsList ( _args , no_argv = True )
async def stop ( self ) : """Safely shut down this interface"""
await self . _command_task . future_command ( [ '_set_mode' , 0 , 0 ] ) # Disable advertising await self . _cleanup_old_connections ( ) self . _command_task . stop ( ) self . _stream . stop ( ) self . _serial_port . close ( ) await super ( BLED112Server , self ) . stop ( )
def ignore ( self , matcher ) : '''Unblock and ignore the matched events , if any .'''
events = self . eventtree . findAndRemove ( matcher ) for e in events : self . queue . unblock ( e ) e . canignore = True
def get_output_str ( item , detect_numerics , precision , sign_value ) : """Returns the final string which should be displayed"""
if detect_numerics : item = _convert_to_numeric ( item ) if isinstance ( item , float ) : item = round ( item , precision ) try : item = '{:{sign}}' . format ( item , sign = sign_value ) except ( ValueError , TypeError ) : pass return to_unicode ( item )
def get_domain ( self ) : """: returns : opposite vertices of the bounding prism for this object . : rtype : ndarray ( [ min ] , [ max ] )"""
points = np . vstack ( [ place . get_domain ( ) for place in self ] ) return np . array ( [ points . min ( axis = 0 ) , points . max ( axis = 0 ) ] )
def expected_log_likelihood ( self , mus , sigmas , y ) : """Compute the expected log likelihood for a mean and covariance of x and an observed value of y ."""
# Flatten the covariance T = mus . shape [ 0 ] D = self . D_in sigs_vec = sigmas . reshape ( ( T , D ** 2 ) ) # Compute the log likelihood of each column ll = np . zeros ( ( T , self . D_out ) ) for n in range ( self . D_out ) : an = self . A [ n ] E_loglmbda = np . dot ( mus , an ) ll [ : , n ] += y [ : , ...
def control ( self ) : """control : ' if ' ctrl _ exp block ( ' elif ' ctrl _ exp block ) * ( ' else ' block )"""
self . eat ( TokenTypes . IF ) ctrl = self . expression ( ) block = self . block ( ) ifs = [ If ( ctrl , block ) ] else_block = Block ( ) while self . cur_token . type == TokenTypes . ELIF : self . eat ( TokenTypes . ELIF ) ctrl = self . expression ( ) block = self . block ( ) ifs . append ( If ( ctrl ,...
def version_router ( self , request , response , api_version = None , versions = { } , not_found = None , ** kwargs ) : """Intelligently routes a request to the correct handler based on the version being requested"""
request_version = self . determine_version ( request , api_version ) if request_version : request_version = int ( request_version ) versions . get ( request_version or False , versions . get ( None , not_found ) ) ( request , response , api_version = api_version , ** kwargs )
def __call ( self , * args , ** kwargs ) : '''Call Zypper . : param state : : return :'''
self . __called = True if self . __xml : self . __cmd . append ( '--xmlout' ) if not self . __refresh and '--no-refresh' not in args : self . __cmd . append ( '--no-refresh' ) if self . __root : self . __cmd . extend ( [ '--root' , self . __root ] ) self . __cmd . extend ( args ) kwargs [ 'output_loglevel' ...
def enable_i2c_slave ( self , slave_address ) : """Enable I2C slave mode . The device will respond to the specified slave _ address if it is addressed . You can wait for the data with : func : ` poll ` and get it with ` i2c _ slave _ read ` ."""
ret = api . py_aa_i2c_slave_enable ( self . handle , slave_address , self . BUFFER_SIZE , self . BUFFER_SIZE ) _raise_error_if_negative ( ret )
def smoothed ( self , angle = .4 ) : """Return a version of the current mesh which will render nicely , without changing source mesh . Parameters angle : float Angle in radians , face pairs with angles smaller than this value will appear smoothed Returns smoothed : trimesh . Trimesh Non watertight v...
# smooth should be recomputed if visuals change self . visual . _verify_crc ( ) cached = self . visual . _cache [ 'smoothed' ] if cached is not None : return cached smoothed = graph . smoothed ( self , angle ) self . visual . _cache [ 'smoothed' ] = smoothed return smoothed
def _calendar_month_middles ( year ) : """List of middle day of each month , used by Linke turbidity lookup"""
# remove mdays [ 0 ] since January starts at mdays [ 1] # make local copy of mdays since we need to change # February for leap years mdays = np . array ( calendar . mdays [ 1 : ] ) ydays = 365 # handle leap years if calendar . isleap ( year ) : mdays [ 1 ] = mdays [ 1 ] + 1 ydays = 366 middles = np . concatenat...
def _get_pages ( page_size , total_records ) : """Given a page size ( records per page ) and a total number of records , return the page numbers to be retrieved ."""
pages = total_records / page_size + bool ( total_records % page_size ) return range ( 1 , pages + 1 )
def cleanup ( self ) : """Delete expired nonces"""
t = time . time ( ) for noncefile in glob ( self . path + '/*.nonce' ) : if os . path . getmtime ( noncefile ) + self . expiration > t : os . unlink ( noncefile )
def transitive_invalidation_hash ( self , fingerprint_strategy = None , depth = 0 ) : """: API : public : param FingerprintStrategy fingerprint _ strategy : optional fingerprint strategy to use to compute the fingerprint of a target : return : A fingerprint representing this target and all of its dependencies...
if depth > self . _MAX_RECURSION_DEPTH : # NB ( zundel ) without this catch , we ' ll eventually hit the python stack limit # RuntimeError : maximum recursion depth exceeded while calling a Python object raise self . RecursiveDepthError ( "Max depth of {} exceeded." . format ( self . _MAX_RECURSION_DEPTH ) ) finger...
def set_ ( dic , path , val , seps = PATH_SEPS ) : """setter for nested dicts . : param dic : a dict [ - like ] object support recursive merge operations : param path : Path expression to point object wanted : param seps : Separator char candidates > > > d = dict ( a = 1 , b = dict ( c = 2 , ) ) > > > set...
merge ( dic , mk_nested_dic ( path , val , seps ) , ac_merge = MS_DICTS )
def get_friends_list ( self , steamID , relationship = 'all' , format = None ) : """Request the friends list of a given steam ID filtered by role . steamID : The user ID relationship : Type of friend to request ( all , friend ) format : Return format . None defaults to json . ( json , xml , vdf )"""
parameters = { 'steamid' : steamID , 'relationship' : relationship } if format is not None : parameters [ 'format' ] = format url = self . create_request_url ( self . interface , 'GetFriendsList' , 1 , parameters ) data = self . retrieve_request ( url ) return self . return_data ( data , format = format )
def rvs ( self , random_state = None ) : r"""Draw a random value from this Parameter ' s distribution . If ` ` value ` ` was not initialised with a ` ` scipy . stats ` ` object , then the scalar / ndarray value is returned . Parameters random _ state : None , int or RandomState , optional random seed Re...
# No sampling distibution if self . dist is None : return self . value # Unconstrained samples rs = check_random_state ( random_state ) samples = self . dist . rvs ( size = self . shape , random_state = rs ) # Bound the samples samples = self . bounds . clip ( samples ) return samples
def draw_pathcollection ( data , obj ) : """Returns PGFPlots code for a number of patch objects ."""
content = [ ] # gather data assert obj . get_offsets ( ) is not None labels = [ "x" + 21 * " " , "y" + 21 * " " ] dd = obj . get_offsets ( ) draw_options = [ "only marks" ] table_options = [ ] if obj . get_array ( ) is not None : draw_options . append ( "scatter" ) dd = numpy . column_stack ( [ dd , obj . get_a...
def set_alpha ( node , alpha = 0.1 ) : """Sets all a ( lpha ) field of the rgba attribute to be @ alpha for @ node and all subnodes used for managing display"""
for child_node in node . findall ( ".//*[@rgba]" ) : rgba_orig = string_to_array ( child_node . get ( "rgba" ) ) child_node . set ( "rgba" , array_to_string ( list ( rgba_orig [ 0 : 3 ] ) + [ alpha ] ) )
def matchFileOnDirPath ( curpath , pathdir ) : """Find match for a file by slicing away its directory elements from the front and replacing them with pathdir . Assume that the end of curpath is right and but that the beginning may contain some garbage ( or it may be short ) Overlaps are allowed : e . g / ...
if os . path . exists ( curpath ) : return curpath filedirs = curpath . split ( '/' ) [ 1 : ] filename = filedirs [ - 1 ] filedirs = filedirs [ : - 1 ] if pathdir [ - 1 ] == '/' : pathdir = pathdir [ : - 1 ] # assume absolute paths pathdirs = pathdir . split ( '/' ) [ 1 : ] lp = len ( pathdirs ) # Cut off match...
def _raise_bad_scheme ( cls , scheme , valid , msg ) : """Raise : attr : ` BadScheme ` error for ` ` scheme ` ` , possible valid scheme are in ` ` valid ` ` , the error message is ` ` msg ` ` : param bytes scheme : A bad scheme : param list valid : A list a valid scheme : param str msg : The error template ...
valid_schemes = [ s . decode ( ) for s in valid ] valid_schemes . sort ( ) raise cls . BadScheme ( msg % ( scheme , u", " . join ( valid_schemes ) ) )
def prior_rvs ( self , size = 1 , prior = None ) : """Returns random variates drawn from the prior . If the ` ` sampling _ params ` ` are different from the ` ` variable _ params ` ` , the variates are transformed to the ` sampling _ params ` parameter space before being returned . Parameters size : int ,...
# draw values from the prior if prior is None : prior = self . prior_distribution p0 = prior . rvs ( size = size ) # transform if necessary if self . sampling_transforms is not None : ptrans = self . sampling_transforms . apply ( p0 ) # pull out the sampling args p0 = FieldArray . from_arrays ( [ ptrans...
def rollout ( env , acts ) : """Perform a rollout using a preset collection of actions"""
total_rew = 0 env . reset ( ) steps = 0 for act in acts : _obs , rew , done , _info = env . step ( act ) steps += 1 total_rew += rew if done : break return steps , total_rew
def zip_dir ( dir_path , zip_file ) : """Creates a zip file of a directory tree This method creates a zip archive using the directory tree dir _ path and adds to zip _ file output . : param dir _ path : ( str ) Full path to directory to be zipped : param zip _ file : ( str ) Full path to the output zip file...
log = logging . getLogger ( mod_logger + '.zip_dir' ) # Validate args if not isinstance ( dir_path , basestring ) : msg = 'dir_path argument must be a string' log . error ( msg ) raise CommandError ( msg ) if not isinstance ( zip_file , basestring ) : msg = 'zip_file argument must be a string' log ....
async def device_info ( ) : """Get device info from GH ."""
async with aiohttp . ClientSession ( ) as session : ghlocalapi = NetworkScan ( LOOP , session ) result = await ghlocalapi . scan_for_units ( IPRANGE ) print ( result )
def most_frequent ( self , k ) : """Returns a vocabulary with the most frequent ` k ` words . Args : k ( integer ) : specifies the top k most frequent words to be returned ."""
word_count = { w : self . word_count [ w ] for w in self . words [ : k ] } return CountedVocabulary ( word_count = word_count )
def __set_lost_stop_status ( self , hgvs_string ) : """Check if the stop codon was mutated to something other than a stop codon ."""
lost_stop_pattern = '^\*\d+[A-Z?]+\*?$' if re . search ( lost_stop_pattern , hgvs_string ) : self . is_lost_stop = True self . is_non_silent = True else : self . is_lost_stop = False
def get_global_parameters ( config_names = ( "core" , "scheduler" , "worker" , "retcode" ) ) : """Returns a list of global , luigi - internal configuration parameters . Each list item is a 4 - tuple containing the configuration class , the parameter instance , the parameter name , and the full parameter name in...
params = [ ] for cls in luigi . task . Config . __subclasses__ ( ) : if config_names and cls . __name__ not in config_names : continue for attr in dir ( cls ) : param = getattr ( cls , attr ) if not isinstance ( param , luigi . Parameter ) : continue full_name = attr ...
def vsreenqueue ( item_id , item_s , args , ** kwargs ) : '''Enqueue a string , or string - like object to other queues , with arbitrary arguments , sreenqueue is to reenqueue what sprintf is to printf , sreenqueue is to vsreenqueue what sprintf is to vsprintf .'''
charset = kwargs . get ( 'charset' , _c . FSQ_CHARSET ) if kwargs . has_key ( 'charset' ) : del kwargs [ 'charset' ] kwargs [ 'item_id' ] = item_id # we coerce here because StringIO . StringIO will coerce on file - write , # and cStringIO . StringIO has a bug which injects NULs for unicode if isinstance ( item_s , ...
def _reset_em ( self ) : """Resets self . em and the shared instances ."""
self . em = _ExtendedManager ( self . addr , self . authkey , mode = self . mode , start = False ) self . em . start ( ) self . _set_shared_instances ( )
def L_unsupported_max ( Do , material = 'CS' ) : r'''Determines the maximum length of a heat exchanger tube can go without a support , acording to TEMA [ 1 ] _ . The limits provided apply for the worst - case temperature allowed for the material to be used at . Parameters Do : float Outer tube diameter , ...
Do = Do / inch # convert diameter to inches i = bisect ( _L_unsupported_Do , Do ) - 1 i = i if i < 11 else 11 # bisect returns 1 + if above the index i = 0 if i == - 1 else i if material == 'CS' : return _L_unsupported_steel [ i ] elif material == 'aluminium' : return _L_unsupported_aluminium [ i ] else : r...
def from_dict ( cls , raw_data , ** kwargs ) : """This factory for : class : ` Model ` creates a Model from a dict object ."""
instance = cls ( ) instance . populate ( raw_data , ** kwargs ) instance . validate ( ** kwargs ) return instance
def getresponse ( self ) : """Pass - thru method to make this class behave a little like HTTPConnection"""
resp = self . http . getresponse ( ) self . log . info ( "resp is %s" , str ( resp ) ) if resp . status < 400 : return resp else : errtext = resp . read ( ) content_type = resp . getheader ( 'Content-Type' , 'text/plain' ) raise HttpError ( code = resp . status , content_type = content_type , content = ...
def always_fail ( cls , request ) -> [ ( 200 , 'Ok' , String ) , ( 406 , 'Not Acceptable' , Void ) ] : '''Perform an always failing task .'''
task_id = uuid4 ( ) . hex . upper ( ) [ : 5 ] log . info ( 'Starting always FAILING task {}' . format ( task_id ) ) for i in range ( randint ( 0 , MAX_LOOP_DURATION ) ) : yield Respond ( 406 ) Respond ( 200 , 'Foobar' )
def __process ( self , event ) : """处理事件"""
# 检查是否存在对该事件进行监听的处理函数 if event . type_ in self . __handlers : # 若存在 , 则按顺序将事件传递给处理函数执行 [ handler ( event ) for handler in self . __handlers [ event . type_ ] ] # 以上语句为Python列表解析方式的写法 , 对应的常规循环写法为 : # for handler in self . _ _ handlers [ event . type _ ] : # handler ( event ) # 调用通用处理函数进行处理 if self . __g...
def _clean_frequency ( frequency ) : """Converts a frequency value to an integer . Raises an error if an invalid type is given . : param frequency : A frequency : type frequency : int or datetime . timedelta : rtype : int"""
if isinstance ( frequency , int ) : return frequency elif isinstance ( frequency , datetime . timedelta ) : return int ( frequency . total_seconds ( ) ) raise ValueError ( 'Invalid frequency {!r}' . format ( frequency ) )
def _write_export ( export , file_obj = None ) : """Write a string to a file . If file _ obj isn ' t specified , return the string Parameters export : a string of the export data file _ obj : a file - like object or a filename"""
if file_obj is None : return export if hasattr ( file_obj , 'write' ) : out_file = file_obj else : out_file = open ( file_obj , 'wb' ) try : out_file . write ( export ) except TypeError : out_file . write ( export . encode ( 'utf-8' ) ) out_file . close ( ) return export
def merge_core ( objs , compat = 'broadcast_equals' , join = 'outer' , priority_arg = None , explicit_coords = None , indexes = None ) : """Core logic for merging labeled objects . This is not public API . Parameters objs : list of mappings All values must be convertable to labeled arrays . compat : { ' i...
# noqa from . dataset import calculate_dimensions _assert_compat_valid ( compat ) coerced = coerce_pandas_values ( objs ) aligned = deep_align ( coerced , join = join , copy = False , indexes = indexes ) expanded = expand_variable_dicts ( aligned ) coord_names , noncoord_names = determine_coords ( coerced ) priority_va...
def cmd_guided ( self , args ) : '''set GUIDED target'''
if len ( args ) != 1 and len ( args ) != 3 : print ( "Usage: guided ALTITUDE | guided LAT LON ALTITUDE" ) return if len ( args ) == 3 : latitude = float ( args [ 0 ] ) longitude = float ( args [ 1 ] ) altitude = float ( args [ 2 ] ) latlon = ( latitude , longitude ) else : try : latl...
def _set_arp_node_config ( self , v , load = False ) : """Setter method for arp _ node _ config , mapped from YANG variable / interface / tengigabitethernet / ip / arp _ node _ config ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ arp _ node _ config is c...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = arp_node_config . arp_node_config , is_container = 'container' , presence = False , yang_name = "arp-node-config" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , regist...
def start_exp ( ) : """Serves up the experiment applet ."""
if not ( ( 'hitId' in request . args ) and ( 'assignmentId' in request . args ) and ( 'workerId' in request . args ) and ( 'mode' in request . args ) ) : raise ExperimentError ( 'hit_assign_worker_id_not_set_in_exp' ) hit_id = request . args [ 'hitId' ] assignment_id = request . args [ 'assignmentId' ] worker_id = ...
def seconds_to_hms ( input_seconds ) : """Convert seconds to human - readable time ."""
minutes , seconds = divmod ( input_seconds , 60 ) hours , minutes = divmod ( minutes , 60 ) hours = int ( hours ) minutes = int ( minutes ) seconds = str ( int ( seconds ) ) . zfill ( 2 ) return hours , minutes , seconds
def assign_methods ( self , resource_class ) : """Given a resource _ class and it ' s Meta . methods tuple , assign methods for communicating with that resource . Args : resource _ class : A single resource class"""
assert all ( [ x . upper ( ) in VALID_METHODS for x in resource_class . Meta . methods ] ) for method in resource_class . Meta . methods : self . _assign_method ( resource_class , method . upper ( ) )
def _maximize ( self ) : """Find argmax of the acquisition function ."""
if not self . space . is_observations_valid ( ) : return None y_max = self . space . y . max ( ) self . utility_function . gaussian_process . fit ( self . space . x , self . space . y ) return self . utility_function . max_compute ( y_max = y_max , bounds = self . space . bounds , n_warmup = self . n_warmup , n_ite...
def paragraphs ( value ) : """Blank lines delimitates paragraphs ."""
result = "\n\n" . join ( "<p>{}</p>" . format ( p . strip ( ) . replace ( "\n" , Markup ( "<br />\n" ) ) ) for p in _PARAGRAPH_RE . split ( escape ( value ) ) ) return result
def _isReactiveMarket ( self ) : """Returns a flag indicating the existance of offers / bids for reactive power ."""
vLoads = [ g for g in self . case . generators if g . is_load ] if [ offbid for offbid in self . offers + self . bids if offbid . reactive ] : haveQ = True logger . warning ( "Combined active/reactive power " "market not yet implemented." ) raise NotImplementedError else : haveQ = False combinedTypes = ...
def translate_filenames ( filenames ) : """Convert filenames from Linux to Windows ."""
if is_windows ( ) : return filenames for index , filename in enumerate ( filenames ) : filenames [ index ] = vboxsf_to_windows ( filename )
def allows_url ( self , url_data ) : """Ask robots . txt allowance ."""
roboturl = url_data . get_robots_txt_url ( ) with self . get_lock ( roboturl ) : return self . _allows_url ( url_data , roboturl )
def load_notebook ( resources = None , verbose = False , hide_banner = False , load_timeout = 5000 ) : '''Prepare the IPython notebook for displaying Bokeh plots . Args : resources ( Resource , optional ) : how and where to load BokehJS from ( default : CDN ) verbose ( bool , optional ) : whether to repor...
global _NOTEBOOK_LOADED from . . import __version__ from . . core . templates import NOTEBOOK_LOAD from . . util . serialization import make_id from . . resources import CDN from . . util . compiler import bundle_all_models if resources is None : resources = CDN if not hide_banner : if resources . mode == 'inli...
def create_project ( self , name , ** kwargs ) : """Creates a project with a name . All other parameters are optional . They are : ` note ` , ` customer _ id ` , ` budget ` , ` budget _ type ` , ` active _ hourly _ rate ` , ` hourly _ rate ` , ` hourly _ rates _ per _ service ` , and ` archived ` ."""
data = self . _wrap_dict ( "project" , kwargs ) data [ "customer" ] [ "name" ] = name return self . post ( "/projects.json" , data = data )
def create ( prefix , params , hint ) : """Creates prefix and params for new ` Block ` ."""
current = getattr ( _BlockScope . _current , "value" , None ) if current is None : if prefix is None : if not hasattr ( _name . NameManager . _current , "value" ) : _name . NameManager . _current . value = _name . NameManager ( ) prefix = _name . NameManager . _current . value . get ( No...
def source_bash ( args , stdin = None ) : """Simply bash - specific wrapper around source - foreign Returns a dict to be used as a new environment"""
args = list ( args ) new_args = [ 'bash' , '--sourcer=source' ] new_args . extend ( args ) return source_foreign ( new_args , stdin = stdin )
def set ( self , key , value , confidence = 100 ) : """Defines the given value with the given confidence , unless the same value is already defined with a higher confidence level ."""
if value is None : return if key in self . info : old_confidence , old_value = self . info . get ( key ) if old_confidence >= confidence : return self . info [ key ] = ( confidence , value )
def _get_team_results ( self , away_name , away_abbr , away_score , home_name , home_abbr , home_score ) : """Determine the winner and loser of the game . If the game has been completed and sports - reference has been updated with the score , determine the winner and loser and return their respective names an...
if not away_score or not home_score : return None , None if away_score > home_score : return ( away_name , away_abbr ) , ( home_name , home_abbr ) else : return ( home_name , home_abbr ) , ( away_name , away_abbr )
def create ( self , name ) : """Create a new vgroup , and assign it a name . Args : : name name to assign to the new vgroup Returns : : VG instance for the new vgroup A create ( name ) call is equivalent to an attach ( - 1 , 1 ) call , followed by a call to the setname ( name ) method of the instance . ...
vg = self . attach ( - 1 , 1 ) vg . _name = name return vg
def render ( self , form , form_style , context ) : """Renders an ` < input / > ` if container is used as a Layout object"""
return render_to_string ( self . template , Context ( { 'input' : self } ) )
def process ( self , metric ) : """Process a metric by doing nothing"""
self . log . debug ( "Metric: %s" , str ( metric ) . rstrip ( ) . replace ( ' ' , '\t' ) )
def _log_failure ( arg_num , msg = None ) : """Retrace stack and log the failed expresion information"""
# stack ( ) returns a list of frame records # 0 is the _ log _ failure ( ) function # 1 is the expect ( ) function # 2 is the function that called expect ( ) , that ' s what we want # a frame record is a tuple like this : # ( frame , filename , line , funcname , contextlist , index ) # we ' re only interested in the fi...
def filter ( self , filter_func , reverse = False ) : """Filter current log lines by a given filter function . This allows to drill down data out of the log file by filtering the relevant log lines to analyze . For example , filter by a given IP so only log lines for that IP are further processed with comma...
new_log_file = Log ( ) new_log_file . logfile = self . logfile new_log_file . total_lines = 0 new_log_file . _valid_lines = [ ] new_log_file . _invalid_lines = self . _invalid_lines [ : ] # add the reverse conditional outside the loop to keep the loop as # straightforward as possible if not reverse : for i in self ...
def decrypt ( self , msg ) : """decrypt a message"""
error = False signature = msg [ 0 : SHA256 . digest_size ] iv = msg [ SHA256 . digest_size : SHA256 . digest_size + AES . block_size ] cipher_text = msg [ SHA256 . digest_size + AES . block_size : ] if self . sign ( iv + cipher_text ) != signature : error = True ctr = Counter . new ( AES . block_size * 8 , initial_...
def queue ( self , queue , message , params = { } , uids = [ ] ) : """Queue a job in Rhumba"""
d = { 'id' : uuid . uuid1 ( ) . get_hex ( ) , 'version' : 1 , 'message' : message , 'params' : params } if uids : for uid in uids : yield self . client . lpush ( 'rhumba.dq.%s.%s' % ( uid , queue ) , json . dumps ( d ) ) else : yield self . client . lpush ( 'rhumba.q.%s' % queue , json . dumps ( d ) ) d...
def _update_trsys ( self , event ) : """Called when has changed . This allows the node and its children to react ( notably , VisualNode uses this to update its TransformSystem ) . Note that this method is only called when one transform is replaced by another ; it is not called if an existing transform inter...
for ch in self . children : ch . _update_trsys ( event ) self . events . transform_change ( ) self . update ( )
def move ( self , queue , delay = 0 , depends = None ) : '''Move this job out of its existing state and into another queue . If a worker has been given this job , then that worker ' s attempts to heartbeat that job will fail . Like ` ` Queue . put ` ` , this accepts a delay , and dependencies'''
logger . info ( 'Moving %s to %s from %s' , self . jid , queue , self . queue_name ) return self . client ( 'put' , self . worker_name , queue , self . jid , self . klass_name , json . dumps ( self . data ) , delay , 'depends' , json . dumps ( depends or [ ] ) )
def decode_token ( token ) : """Top - level method to decode a JWT . Takes either a compact - encoded JWT with a single signature , or a multi - sig JWT in the JSON - serialized format . Returns the deserialized token , as a dict . The signatures will still be base64 - encoded"""
if isinstance ( token , ( unicode , str ) ) : return _decode_token_compact ( token ) else : return _decode_token_json ( token )
def get_resource_component_children ( self , resource_component_id ) : """Given a resource component , fetches detailed metadata for it and all of its children . This is implemented using ArchivesSpaceClient . get _ resource _ component _ children and uses its default options when fetching children . : param st...
resource_type = self . resource_type ( resource_component_id ) return self . get_resource_component_and_children ( resource_component_id , resource_type )
def _assemble_regulate_activity ( stmt ) : """Assemble RegulateActivity statements into text ."""
subj_str = _assemble_agent_str ( stmt . subj ) obj_str = _assemble_agent_str ( stmt . obj ) if stmt . is_activation : rel_str = ' activates ' else : rel_str = ' inhibits ' stmt_str = subj_str + rel_str + obj_str return _make_sentence ( stmt_str )
def _create_tc_dirs ( self ) : """Create app directories for logs and data files ."""
tc_log_path = self . profile . get ( 'args' , { } ) . get ( 'tc_log_path' ) if tc_log_path is not None and not os . path . isdir ( tc_log_path ) : os . makedirs ( tc_log_path ) tc_out_path = self . profile . get ( 'args' , { } ) . get ( 'tc_out_path' ) if tc_out_path is not None and not os . path . isdir ( tc_out_p...
def layers ( self , value : List [ 'BaseLayer' ] ) : """Perform a copy of the layers list in order to avoid the list changing without updating the index . Then update the index ."""
self . _layers = list ( value ) # type : List [ BaseLayer ] self . _index = self . _make_index ( ) self . _transformed = { }
def _url ( self ) : """Get the URL for the resource"""
if self . ID_NAME not in self . route . keys ( ) and "id" in self . data . keys ( ) : self . route [ self . ID_NAME ] = self . data [ "id" ] return self . config . BASE + self . PATH . format ( ** self . route )
def init_widget ( self ) : """Initialize the underlying widget . This reads all items declared in the enamldef block for this node and sets only the values that have been specified . All other values will be left as default . Doing it this way makes atom to only create the properties that need to be overrid...
super ( AndroidView , self ) . init_widget ( ) # Initialize the widget by updating only the members that # have read expressions declared . This saves a lot of time and # simplifies widget initialization code for k , v in self . get_declared_items ( ) : handler = getattr ( self , 'set_' + k , None ) if handler ...
def convert_weka_to_py_date_pattern ( p ) : """Converts the date format pattern used by Weka to the date format pattern used by Python ' s datetime . strftime ( ) ."""
# https : / / docs . python . org / 2 / library / datetime . html # strftime - strptime - behavior # https : / / www . cs . waikato . ac . nz / ml / weka / arff . html p = p . replace ( 'yyyy' , r'%Y' ) p = p . replace ( 'MM' , r'%m' ) p = p . replace ( 'dd' , r'%d' ) p = p . replace ( 'HH' , r'%H' ) p = p . replace ( ...
def ld_cifar10 ( ) : """Load training and test data ."""
train_transforms = torchvision . transforms . Compose ( [ torchvision . transforms . ToTensor ( ) ] ) test_transforms = torchvision . transforms . Compose ( [ torchvision . transforms . ToTensor ( ) ] ) train_dataset = torchvision . datasets . CIFAR10 ( root = '/tmp/data' , train = True , transform = train_transforms ,...
def decode_format ( number_format ) : """Convert style string to format string ( ' { } ' style ) , suffix and value scale This is the core function used to convert numbers to strings"""
style = number_format [ 0 ] prec = "." + str ( int ( number_format [ 1 : ] ) ) if len ( number_format ) > 1 else "" if style == NUMBER : return "," + prec + "g" , "" , 1. elif style == THOUSANDS : return "," + prec + "g" , "k" , 1e-3 elif style == MILLIONS : return "," + prec + "g" , "m" , 1e-6 elif style =...
def add_member ( self , service_name , servicegroup_name ) : """Add a member ( service ) to this servicegroup : param service _ name : member ( service ) name : type service _ name : str : param servicegroup _ name : servicegroup name : type servicegroup _ name : str : return : None"""
servicegroup = self . find_by_name ( servicegroup_name ) if not servicegroup : servicegroup = Servicegroup ( { 'servicegroup_name' : servicegroup_name , 'alias' : servicegroup_name , 'members' : service_name } ) self . add ( servicegroup ) else : servicegroup . add_members ( service_name )
def new ( self , ** kwargs ) : '''Return a new ` ` Message ` ` instance . The arguments are passed to the ` ` marrow . mailer . Message ` ` constructor .'''
app = self . app or current_app mailer = app . extensions [ 'marrowmailer' ] msg = mailer . new ( ** kwargs ) msg . __class__ = Message return msg
def _get_hash_by_shell ( ) : '''Shell - out Python 3 for compute reliable hash : return :'''
id_ = __opts__ . get ( 'id' , '' ) id_hash = None py_ver = sys . version_info [ : 2 ] if py_ver >= ( 3 , 3 ) : # Python 3.3 enabled hash randomization , so we need to shell out to get # a reliable hash . id_hash = __salt__ [ 'cmd.run' ] ( [ sys . executable , '-c' , 'print(hash("{0}"))' . format ( id_ ) ] , env = {...
def randset ( self ) : """- > a # set of random integers"""
return { self . _map_type ( int ) for x in range ( self . random . randint ( 3 , 10 ) ) }
def stop ( self ) : """Signals the worker threads to exit and waits on them ."""
if not self . stopped ( ) : self . _stop . set ( ) for worker in self . _workers : worker . join ( )
def _write_symlink ( self , zf , link_target , link_path ) : """Package symlinks with appropriate zipfile metadata ."""
info = zipfile . ZipInfo ( ) info . filename = link_path info . create_system = 3 # Magic code for symlinks / py2/3 compat # 27166663808 = ( stat . S _ IFLNK | 0755 ) < < 16 info . external_attr = 2716663808 zf . writestr ( info , link_target )