signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_file_list ( path , max_depth = 1 , cur_depth = 0 ) : """Recursively returns a list of all files up to ` ` max _ depth ` ` in a directory ."""
if os . path . exists ( path ) : for name in os . listdir ( path ) : if name . startswith ( '.' ) : continue full_path = os . path . join ( path , name ) if os . path . isdir ( full_path ) : if cur_depth == max_depth : continue file_list = ...
def get_global_shelf_fpath ( appname = 'default' , ensure = False ) : """Returns the filepath to the global shelf"""
global_cache_dir = get_global_cache_dir ( appname , ensure = ensure ) shelf_fpath = join ( global_cache_dir , meta_util_constants . global_cache_fname ) return shelf_fpath
def save_config ( self , filepath ) : """saves gui configuration to out _ file _ name Args : filepath : name of file"""
def get_hidden_parameter ( item ) : num_sub_elements = item . childCount ( ) if num_sub_elements == 0 : dictator = { item . name : item . visible } else : dictator = { item . name : { } } for child_id in range ( num_sub_elements ) : dictator [ item . name ] . update ( get...
def set_active_scalar ( self , name , preference = 'cell' ) : """Finds the scalar by name and appropriately sets it as active"""
_ , field = get_scalar ( self , name , preference = preference , info = True ) if field == POINT_DATA_FIELD : self . GetPointData ( ) . SetActiveScalars ( name ) elif field == CELL_DATA_FIELD : self . GetCellData ( ) . SetActiveScalars ( name ) else : raise RuntimeError ( 'Data field ({}) not useable' . for...
def eventsource_connect ( url , io_loop = None , callback = None , connect_timeout = None ) : """Client - side eventsource support . Takes a url and returns a Future whose result is a ` EventSourceClient ` ."""
if io_loop is None : io_loop = IOLoop . current ( ) if isinstance ( url , httpclient . HTTPRequest ) : assert connect_timeout is None request = url # Copy and convert the headers dict / object ( see comments in # AsyncHTTPClient . fetch ) request . headers = httputil . HTTPHeaders ( request . he...
def getClassInPackageFromName ( className , pkg ) : """get a class from name within a package"""
# TODO : more efficiency ! n = getAvClassNamesInPackage ( pkg ) i = n . index ( className ) c = getAvailableClassesInPackage ( pkg ) return c [ i ]
def _get_validation ( self , method , param ) : """Return the correct validations dictionary for this parameter . First checks the method itself and then its class . If no validation is defined for this parameter , None is returned . : param method : A function to get the validation information from . : typ...
if hasattr ( method , '_validations' ) and param in method . _validations : return method . _validations [ param ] elif ( hasattr ( method . im_class , '_validations' ) and param in method . im_class . _validations ) : return method . im_class . _validations [ param ] else : return None
def csnr ( freqs , hc , hn , fmrg , fpeak , prefactor = 1.0 ) : """Calculate the SNR of a frequency domain waveform . SNRCalculation is a function that takes waveforms ( frequencies and hcs ) and a noise curve , and returns SNRs for all binary phases and the whole waveform . Arguments : freqs ( 1D or 2D arr...
cfd = os . path . dirname ( os . path . abspath ( __file__ ) ) if 'phenomd.cpython-35m-darwin.so' in os . listdir ( cfd ) : exec_call = cfd + '/phenomd.cpython-35m-darwin.so' else : exec_call = cfd + '/phenomd/phenomd.so' c_obj = ctypes . CDLL ( exec_call ) # check dimensionality remove_axis = False try : l...
def assign_coords ( self , ** kwargs ) : """Assign new coordinates to this object . Returns a new object with all the original data in addition to the new coordinates . Parameters kwargs : keyword , value pairs keywords are the variables names . If the values are callable , they are computed on this obj...
data = self . copy ( deep = False ) results = self . _calc_assign_results ( kwargs ) data . coords . update ( results ) return data
def FoldValue ( self , value ) : """Folds the data type into a value . Args : value ( object ) : value . Returns : object : folded value . Raises : ValueError : if the data type definition cannot be folded into the value ."""
if value is False and self . _data_type_definition . false_value is not None : return self . _data_type_definition . false_value if value is True and self . _data_type_definition . true_value is not None : return self . _data_type_definition . true_value raise ValueError ( 'No matching True and False values' )
def POST ( self ) : """The HTTP POST body parsed into a MultiDict . This supports urlencoded and multipart POST requests . Multipart is commonly used for file uploads and may result in some of the values beeing cgi . FieldStorage objects instead of strings . Multiple values per key are possible . See MultiD...
if self . _POST is None : save_env = dict ( ) # Build a save environment for cgi for key in ( 'REQUEST_METHOD' , 'CONTENT_TYPE' , 'CONTENT_LENGTH' ) : if key in self . environ : save_env [ key ] = self . environ [ key ] save_env [ 'QUERY_STRING' ] = '' # Without this , sys . argv...
def customer_id ( self , customer_id ) : """Sets the customer _ id of this ChargeRequest . The ID of the customer to associate this transaction with . This field is required if you provide a value for ` customer _ card _ id ` , and optional otherwise . : param customer _ id : The customer _ id of this ChargeReq...
if customer_id is None : raise ValueError ( "Invalid value for `customer_id`, must not be `None`" ) if len ( customer_id ) > 50 : raise ValueError ( "Invalid value for `customer_id`, length must be less than `50`" ) self . _customer_id = customer_id
def update_ledger ( self , ledger_id , description = None ) : """Update ledger info Arguments : ledger _ id : Ledger id assigned by mCASH description : Description of the Ledger and it ' s usage"""
arguments = { 'description' : description } return self . do_req ( 'PUT' , self . merchant_api_base_url + '/ledger/' + ledger_id + '/' , arguments )
def update ( self , data ) : """Update a list ."""
# if self . debug > = 2: # self . debug ( data ) url = "{base}/change_password" . format ( base = self . local_base_url ) self . _check ( data ) res = self . core . create ( url , data ) self . log . debug ( "result: %s" , res ) return res
def Sample ( self , tasks_status ) : """Takes a sample of the status of queued tasks for profiling . Args : tasks _ status ( TasksStatus ) : status information about tasks ."""
sample_time = time . time ( ) sample = '{0:f}\t{1:d}\t{2:d}\t{3:d}\t{4:d}\t{5:d}\n' . format ( sample_time , tasks_status . number_of_queued_tasks , tasks_status . number_of_tasks_processing , tasks_status . number_of_tasks_pending_merge , tasks_status . number_of_abandoned_tasks , tasks_status . total_number_of_tasks ...
def nice_join ( seq , sep = ", " , conjunction = "or" ) : '''Join together sequences of strings into English - friendly phrases using a conjunction when appropriate . Args : seq ( seq [ str ] ) : a sequence of strings to nicely join sep ( str , optional ) : a sequence delimiter to use ( default : " , " ) ...
seq = [ str ( x ) for x in seq ] if len ( seq ) <= 1 or conjunction is None : return sep . join ( seq ) else : return "%s %s %s" % ( sep . join ( seq [ : - 1 ] ) , conjunction , seq [ - 1 ] )
async def _query ( server , method , parameters , timeout = DEFAULT_TIMEOUT , verify_ssl = True , loop : asyncio . AbstractEventLoop = None ) : """Formats and performs the asynchronous query against the API : param server : The server to query . : param method : The method name . : param parameters : A dict o...
api_endpoint = api . get_api_url ( server ) params = dict ( id = - 1 , method = method , params = parameters ) headers = get_headers ( ) ssl_context = None verify = verify_ssl if verify_ssl : ssl_context = ssl . SSLContext ( ssl . PROTOCOL_TLSv1_2 ) conn = aiohttp . TCPConnector ( verify_ssl = verify , ssl_context ...
def create_temp_space ( ) : """Create a new temporary cloud foundry space for a project ."""
# Truncating uuid to just take final 12 characters since space name # is used to name services and there is a 50 character limit on instance # names . # MAINT : hacky with possible collisions unique_name = str ( uuid . uuid4 ( ) ) . split ( '-' ) [ - 1 ] admin = predix . admin . cf . spaces . Space ( ) res = admin . cr...
def _sync_folder_to_container ( self , folder_path , container , prefix , delete , include_hidden , ignore , ignore_timestamps , object_prefix , verbose ) : """This is the internal method that is called recursively to handle nested folder structures ."""
fnames = os . listdir ( folder_path ) ignore = utils . coerce_to_list ( ignore ) log = logging . getLogger ( "pyrax" ) if not include_hidden : ignore . append ( ".*" ) for fname in fnames : if utils . match_pattern ( fname , ignore ) : self . _sync_summary [ "ignored" ] += 1 continue pth = o...
def get_group_list ( user , include_default = True ) : '''Returns a list of all of the system group names of which the user is a member .'''
if HAS_GRP is False or HAS_PWD is False : return [ ] group_names = None ugroups = set ( ) if hasattr ( os , 'getgrouplist' ) : # Try os . getgrouplist , available in python > = 3.3 log . trace ( 'Trying os.getgrouplist for \'%s\'' , user ) try : group_names = [ grp . getgrgid ( grpid ) . gr_name for...
def registerParentFlag ( self , optionName , value ) : '''Register a flag of a parent command : Parameters : - ` optionName ` : String . Name of option - ` value ` : Mixed . Value of parsed flag `'''
self . parentFlags . update ( { optionName : value } ) return self
def _connected ( self , transport , conn ) : """Login and sync the ElkM1 panel to memory ."""
LOG . info ( "Connected to ElkM1" ) self . _conn = conn self . _transport = transport self . _connection_retry_timer = 1 if url_scheme_is_secure ( self . _config [ 'url' ] ) : self . _conn . write_data ( self . _config [ 'userid' ] , raw = True ) self . _conn . write_data ( self . _config [ 'password' ] , raw =...
def make_parts_for ( self , field_name , field_data ) : """Create the relevant parts for this field Args : field _ name ( str ) : Short field name , e . g . VAL field _ data ( FieldData ) : Field data object"""
typ = field_data . field_type subtyp = field_data . field_subtype if typ in ( "read" , "xadc" ) : writeable = False else : writeable = True if typ == "time" or typ in ( "param" , "read" ) and subtyp == "time" : self . _make_time_parts ( field_name , field_data , writeable ) elif typ == "write" and subtyp ==...
def log_game_start ( self , players , terrain , numbers , ports ) : """Begin a game . Erase the log , set the timestamp , set the players , and write the log header . The robber is assumed to start on the desert ( or off - board ) . : param players : iterable of catan . game . Player objects : param terrain...
self . reset ( ) self . _set_players ( players ) self . _logln ( '{} v{}' . format ( __name__ , __version__ ) ) self . _logln ( 'timestamp: {0}' . format ( self . timestamp_str ( ) ) ) self . _log_players ( players ) self . _log_board_terrain ( terrain ) self . _log_board_numbers ( numbers ) self . _log_board_ports ( p...
def render ( self , ** kwargs ) : """Renders the HTML representation of the element ."""
self . color_domain = [ self . vmin + ( self . vmax - self . vmin ) * k / 499. for k in range ( 500 ) ] self . color_range = [ self . __call__ ( x ) for x in self . color_domain ] self . tick_labels = legend_scaler ( self . index ) super ( ColorMap , self ) . render ( ** kwargs ) figure = self . get_root ( ) assert isi...
def process_response ( self , request , response ) : """Do nothing , if process _ request never completed ( redirect )"""
if not hasattr ( request , 'location' ) : return response storage = storage_class ( request = request , response = response ) try : storage . set ( location = request . location ) except ValueError : # bad location _ id pass return response
async def servo_config ( self , pin , min_pulse = 544 , max_pulse = 2400 ) : """Configure a pin as a servo pin . Set pulse min , max in ms . Use this method ( not set _ pin _ mode ) to configure a pin for servo operation . : param pin : Servo Pin . : param min _ pulse : Min pulse width in ms . : param max...
command = [ pin , min_pulse & 0x7f , ( min_pulse >> 7 ) & 0x7f , max_pulse & 0x7f , ( max_pulse >> 7 ) & 0x7f ] await self . _send_sysex ( PrivateConstants . SERVO_CONFIG , command )
def CKroneckerLMM_optdelta ( ldelta_opt , A , X , Y , S_C1 , S_R1 , S_C2 , S_R2 , ldeltamin , ldeltamax , numintervals ) : """CKroneckerLMM _ optdelta ( limix : : mfloat _ t & ldelta _ opt , MatrixXdVec A , MatrixXdVec X , MatrixXd const & Y , VectorXd const & S _ C1 , VectorXd const & S _ R1 , VectorXd const & S _...
return _core . CKroneckerLMM_optdelta ( ldelta_opt , A , X , Y , S_C1 , S_R1 , S_C2 , S_R2 , ldeltamin , ldeltamax , numintervals )
def predict ( self , n_periods = 10 , exogenous = None , return_conf_int = False , alpha = 0.05 , ** kwargs ) : """Forecast future ( transformed ) values Generate predictions ( forecasts ) ` ` n _ periods ` ` in the future . Note that if ` ` exogenous ` ` variables were used in the model fit , they will be ex...
check_is_fitted ( self , "steps_" ) # Push the arrays through the transformer stages , but ONLY the exog # transformer stages since we don ' t have a Y . . . Xt = exogenous named_kwargs = self . _get_kwargs ( ** kwargs ) for step_idx , name , transformer in self . _iter ( with_final = False ) : if isinstance ( tran...
def strip_spaces ( s ) : """Strip excess spaces from a string"""
return u" " . join ( [ c for c in s . split ( u' ' ) if c ] )
def b58decode ( v : str ) -> bytes : '''Decode a Base58 encoded string'''
origlen = len ( v ) v = v . lstrip ( alphabet [ 0 ] ) newlen = len ( v ) p , acc = 1 , 0 for c in v [ : : - 1 ] : acc += p * alphabet . index ( c ) p *= 58 result = [ ] while acc > 0 : acc , mod = divmod ( acc , 256 ) result . append ( mod ) return ( bseq ( result ) + b'\0' * ( origlen - newlen ) ) [ : ...
def _create_secret ( namespace , name , data , apiserver_url ) : '''create namespace on the defined k8s cluster'''
# Prepare URL url = "{0}/api/v1/namespaces/{1}/secrets" . format ( apiserver_url , namespace ) # Prepare data request = { "apiVersion" : "v1" , "kind" : "Secret" , "metadata" : { "name" : name , "namespace" : namespace , } , "data" : data } # Make request ret = _kpost ( url , request ) return ret
def remove ( self , song ) : """Remove song from playlist . O ( n ) If song is current song , remove the song and play next . Otherwise , just remove it ."""
if song in self . _songs : if self . _current_song is None : self . _songs . remove ( song ) elif song == self . _current_song : next_song = self . next_song # 随机模式下或者歌单只剩一首歌曲 , 下一首可能和当前歌曲相同 if next_song == self . current_song : self . current_song = None ...
def post_cleanup ( self ) : """remove any divs that looks like non - content , clusters of links , or paras with no gusto"""
targetNode = self . article . top_node node = self . add_siblings ( targetNode ) for e in self . parser . getChildren ( node ) : e_tag = self . parser . getTag ( e ) if e_tag != 'p' : if self . is_highlink_density ( e ) or self . is_table_and_no_para_exist ( e ) or not self . is_nodescore_threshold_met ...
def sagemaker_auth ( overrides = { } , path = "." ) : """Write a secrets . env file with the W & B ApiKey and any additional secrets passed . Args : overrides ( dict , optional ) : Additional environment variables to write to secrets . env path ( str , optional ) : The path to write the secrets file ."""
api_key = overrides . get ( env . API_KEY , Api ( ) . api_key ) if api_key is None : raise ValueError ( "Can't find W&B ApiKey, set the WANDB_API_KEY env variable or run `wandb login`" ) overrides [ env . API_KEY ] = api_key with open ( os . path . join ( path , "secrets.env" ) , "w" ) as file : for k , v in si...
def fetch_genome ( genome_id ) : '''Acquire a genome from Entrez'''
# TODO : Can strandedness by found in fetched genome attributes ? # TODO : skip read / write step ? # Using a dummy email for now - does this violate NCBI guidelines ? email = 'loremipsum@gmail.com' Entrez . email = email print 'Downloading Genome...' handle = Entrez . efetch ( db = 'nucleotide' , id = str ( genome_id ...
def to_hex_twos_compliment ( value , bit_size ) : """Converts integer value to twos compliment hex representation with given bit _ size"""
if value >= 0 : return to_hex_with_size ( value , bit_size ) value = ( 1 << bit_size ) + value hex_value = hex ( value ) hex_value = hex_value . rstrip ( "L" ) return hex_value
def db_group ( self ) : '''str : database system group ( defaults to : attr : ` db _ user < tmdeploy . config . AnsibleHostVariableSection . db _ user > ` )'''
if self . _db_group is None : self . _db_group = self . db_user return self . _db_group
def solve ( self , ** kwargs ) : """The kwargs required depend upon the script type . hash160 _ lookup : dict - like structure that returns a secret exponent for a hash160 existing _ script : existing solution to improve upon ( optional ) sign _ value : the integer value to sign ( derived from the trans...
# we need a hash160 = > secret _ exponent lookup db = kwargs . get ( "hash160_lookup" ) if db is None : raise SolvingError ( "missing hash160_lookup parameter" ) sign_value = kwargs . get ( "sign_value" ) signature_type = kwargs . get ( "signature_type" ) secs_solved = set ( ) existing_signatures = [ ] existing_scr...
def ytdl_progress_hook ( self , d ) : """Called when youtube - dl updates progress"""
if d [ 'status' ] == 'downloading' : self . play_empty ( ) if "elapsed" in d : if d [ "elapsed" ] > self . current_download_elapsed + 4 : self . current_download_elapsed = d [ "elapsed" ] current_download = 0 current_download_total = 0 current_download_eta...
def memory_usage ( proc = - 1 , interval = .1 , timeout = None , timestamps = False , include_children = False , max_usage = False , retval = False , stream = None ) : """Return the memory usage of a process or piece of code Parameters proc : { int , string , tuple , subprocess . Popen } , optional The proces...
if stream is not None : timestamps = True if not max_usage : ret = [ ] else : ret = - 1 if timeout is not None : max_iter = int ( timeout / interval ) elif isinstance ( proc , int ) : # external process and no timeout max_iter = 1 else : # for a Python function wait until it finishes max_iter = ...
def start_tls ( self , ssl_context : Union [ bool , dict , ssl . SSLContext ] = True ) -> 'SSLConnection' : '''Start client TLS on this connection and return SSLConnection . Coroutine'''
sock = self . writer . get_extra_info ( 'socket' ) ssl_conn = SSLConnection ( self . _address , ssl_context = ssl_context , hostname = self . _hostname , timeout = self . _timeout , connect_timeout = self . _connect_timeout , bind_host = self . _bind_host , bandwidth_limiter = self . _bandwidth_limiter , sock = sock ) ...
def poly_energy ( sample_like , poly ) : """Calculates energy of a sample from a higher order polynomial . Args : sample ( samples _ like ) : A raw sample . ` samples _ like ` is an extension of NumPy ' s array _ like structure . See : func : ` . as _ samples ` . poly ( dict ) : Polynomial as a dict of ...
msg = ( "poly_energy is deprecated and will be removed in dimod 0.9.0." "In the future, use BinaryPolynomial.energy" ) warnings . warn ( msg , DeprecationWarning ) # dev note the vartype is not used in the energy calculation and this will # be deprecated in the future return BinaryPolynomial ( poly , 'SPIN' ) . energy ...
def eliminate ( self , node , data ) : """Resolves a source node , passing the message to all associated checks"""
# Cache resolved value self . eliminated [ node ] = data others = self . checks [ node ] del self . checks [ node ] # Pass messages to all associated checks for check in others : check . check ^= data check . src_nodes . remove ( node ) # Yield all nodes that can now be resolved if len ( check . src_nod...
def add_fragment ( self , fragment , as_last = True ) : """Add the given sync map fragment , as the first or last child of the root node of the sync map tree . : param fragment : the sync map fragment to be added : type fragment : : class : ` ~ aeneas . syncmap . fragment . SyncMapFragment ` : param bool ...
if not isinstance ( fragment , SyncMapFragment ) : self . log_exc ( u"fragment is not an instance of SyncMapFragment" , None , True , TypeError ) self . fragments_tree . add_child ( Tree ( value = fragment ) , as_last = as_last )
def process_jpeg_bytes ( bytes_in , quality = DEFAULT_JPEG_QUALITY ) : """Generates an optimized JPEG from JPEG - encoded bytes . : param bytes _ in : the input image ' s bytes : param quality : the output JPEG quality ( default 95) : returns : Optimized JPEG bytes : rtype : bytes : raises ValueError : Gu...
bytes_out_p = ffi . new ( "char**" ) bytes_out_p_gc = ffi . gc ( bytes_out_p , lib . guetzli_free_bytes ) length = lib . guetzli_process_jpeg_bytes ( bytes_in , len ( bytes_in ) , bytes_out_p_gc , quality ) if length == 0 : raise ValueError ( "Invalid JPEG: Guetzli was not able to decode the image" ) # noqa bytes_o...
def get_description_from_docstring ( cls , obj ) : """Returns a pair ( description , details ) from the obj ' s docstring . description is a single line . details is a list of subsequent lines , possibly empty ."""
doc = obj . __doc__ or '' p = doc . find ( '\n' ) if p == - 1 : return doc , [ ] else : description = doc [ : p ] details = textwrap . dedent ( doc [ p + 1 : ] ) . splitlines ( ) # Remove leading and trailing empty lines . while details and not details [ 0 ] . strip ( ) : details = details [...
def get_jobs ( self , name = None ) : """Retrieves jobs running on this resource in its instance . Args : name ( str , optional ) : Only return jobs containing property * * name * * that matches ` name ` . ` name ` can be a regular expression . If ` name ` is not supplied , then all jobs are returned . Retu...
if self . applicationResource : return self . _get_elements ( self . jobs , 'jobs' , Job , None , name ) else : return [ ]
def tick ( self ) : """Ticks the environment once . Normally used for multi - agent environments . Returns : dict : A dictionary from agent name to its full state . The full state is another dictionary from : obj : ` holodeck . sensors . Sensors ` enum to np . ndarray , containing the sensors information fo...
self . _handle_command_buffer ( ) self . _client . release ( ) self . _client . acquire ( ) return self . _get_full_state ( )
def _unapply_interception ( target , ctx = None ) : """Unapply interception on input target in cleaning it . : param routine target : target from where removing an interception function . is _ joinpoint ( target ) must be True . : param ctx : target ctx ."""
# try to get the right ctx if ctx is None : ctx = find_ctx ( elt = target ) # get previous target intercepted , old_ctx = get_intercepted ( target ) # if ctx is None and old _ ctx is not None , update ctx with old _ ctx if ctx is None and old_ctx is not None : ctx = old_ctx if intercepted is None : raise Jo...
def history ( self ) : '''Get history / version information for this datastream and return as an instance of : class : ` ~ eulfedora . xml . DatastreamHistory ` .'''
r = self . obj . api . getDatastreamHistory ( self . obj . pid , self . id , format = 'xml' ) return parse_xml_object ( DatastreamHistory , r . content , r . url )
def get_community_trends ( self , indicator_type = None , days_back = None ) : """Find indicators that are trending in the community . : param indicator _ type : A type of indicator to filter by . If ` ` None ` ` , will get all types of indicators except for MALWARE and CVEs ( this convention is for parity with...
params = { 'type' : indicator_type , 'daysBack' : days_back } resp = self . _client . get ( "indicators/community-trending" , params = params ) body = resp . json ( ) # parse items in response as indicators return [ Indicator . from_dict ( indicator ) for indicator in body ]
def children ( self , alias , bank_id ) : """URL for getting or setting child relationships for the specified bank : param alias : : param bank _ id : : return :"""
return self . _root + self . _safe_alias ( alias ) + '/child/ids/' + str ( bank_id )
def get_group_id ( self , user_id ) : """获取用户所在分组 ID 详情请参考 http : / / mp . weixin . qq . com / wiki / 0/56d992c605a97245eb7e617854b169fc . html : param user _ id : 用户 ID : return : 用户所在分组 ID 使用示例 : : from wechatpy import WeChatClient client = WeChatClient ( ' appid ' , ' secret ' ) group _ id = clie...
res = self . _post ( 'groups/getid' , data = { 'openid' : user_id } , result_processor = lambda x : x [ 'groupid' ] ) return res
def get_event_canned_questions ( self , id , ** data ) : """GET / events / : id / canned _ questions / This endpoint returns canned questions of a single event ( examples : first name , last name , company , prefix , etc . ) . This endpoint will return : format : ` question ` ."""
return self . get ( "/events/{0}/canned_questions/" . format ( id ) , data = data )
def write_info ( self , url_data ) : """Write url _ data . info ."""
self . write ( self . part ( "info" ) + self . spaces ( "info" ) ) self . writeln ( self . wrap ( url_data . info , 65 ) , color = self . colorinfo )
def initialize_environments ( self , batch_size = 1 ) : """Initializes the environments and trajectories . Subclasses can override this if they don ' t want a default implementation which initializes ` batch _ size ` environments , but must take care to initialize self . _ trajectories ( this is checked in _ ...
assert batch_size >= 1 self . _batch_size = batch_size self . _envs = [ gym . make ( self . base_env_name ) for _ in range ( batch_size ) ] if self . _env_wrapper_fn is not None : self . _envs = list ( map ( self . _env_wrapper_fn , self . _envs ) ) # If self . observation _ space and self . action _ space aren ' t...
def synthetic_grad ( X , theta , sigma1 , sigma2 , sigmax , rescale_grad = 1.0 , grad = None ) : """Get synthetic gradient value"""
if grad is None : grad = nd . empty ( theta . shape , theta . context ) theta1 = theta . asnumpy ( ) [ 0 ] theta2 = theta . asnumpy ( ) [ 1 ] v1 = sigma1 ** 2 v2 = sigma2 ** 2 vx = sigmax ** 2 denominator = numpy . exp ( - ( X - theta1 ) ** 2 / ( 2 * vx ) ) + numpy . exp ( - ( X - theta1 - theta2 ) ** 2 / ( 2 * vx ...
def _create_co_virtual_idp ( self , context ) : """Create a virtual IdP to represent the CO . : type context : The current context : rtype : saml . server . Server : param context : : return : An idp server"""
co_name = self . _get_co_name ( context ) context . decorate ( self . KEY_CO_NAME , co_name ) # Verify that we are configured for this CO . If the CO was not # configured most likely the endpoint used was not registered and # SATOSA core code threw an exception before getting here , but we # include this check in case ...
def count_indents_length_last_line ( self , spacecount , tabs = 0 , back = 5 ) : """Finds the last meaningful line and returns its indent level and character length . Back specifies the amount of lines to look back for a none whitespace line ."""
if not self . has_space ( ) : return 0 lines = self . get_surrounding_lines ( back , 0 ) for line in reversed ( lines ) : if not line . string . isspace ( ) : return line . count_indents_length ( spacecount , tabs ) return ( 0 , 0 )
def UpdateArpeggiates ( self , type = "start" ) : '''method which searches for all arpeggiates and updates the top one of each chord to be a start , and the bottom one to be a stop ready for lilypond output : param type : : return :'''
result = self . item . Search ( Arpeggiate ) if result is not None : if type == "start" : result . type = type child = self . GetChild ( 0 ) if child is not None : if child . item . Search ( Arpeggiate ) is None : new_obj = copy . deepcopy ( result ) new_obj . type = ...
def enable ( self ) : """Enable contextual logging"""
with self . _lock : if self . filter is None : self . filter = self . _filter_type ( self )
def _all_fields ( self ) : """Returns the entire serializer field set . Does not respect dynamic field inclusions / exclusions ."""
if ( not settings . ENABLE_FIELDS_CACHE or not self . ENABLE_FIELDS_CACHE or self . __class__ not in FIELDS_CACHE ) : all_fields = super ( WithDynamicSerializerMixin , self ) . get_fields ( ) if ( settings . ENABLE_FIELDS_CACHE and self . ENABLE_FIELDS_CACHE ) : FIELDS_CACHE [ self . __class__ ] = all_f...
def assemble_default_config ( modules ) : """Build the default configuration from a set of modules . ` modules ` is an iterable of : class : ` yakonfig . configurable . Configurable ` objects , or anything equivalently typed . This produces the default configuration from that list of modules . : param mod...
def work_in ( parent_config , config_name , prefix , module ) : my_config = dict ( getattr ( module , 'default_config' , { } ) ) if config_name in parent_config : extra_config = parent_config [ config_name ] raise ProgrammerError ( 'config for {0} already present when about to fetch {3}.default_...
def stop ( self , timeout = 1.0 ) : """Stop a running server ( from another thread ) . Parameters timeout : float , optional Seconds to wait for server to have * started * . Returns stopped : thread - safe Future Resolves when the server is stopped"""
stopped = self . _server . stop ( timeout ) if self . _handler_thread : self . _handler_thread . stop ( timeout ) return stopped
def set_configuration ( self , message_number = default_message_number , exception_number = default_exception_number , permanent_progressbar_slots = default_permanent_progressbar_slots , redraw_frequency_millis = default_redraw_frequency_millis , console_level = default_level , task_millis_to_removal = default_task_mil...
self . queue . put ( dill . dumps ( SetConfigurationCommand ( task_millis_to_removal = task_millis_to_removal , console_level = console_level , permanent_progressbar_slots = permanent_progressbar_slots , message_number = message_number , exception_number = exception_number , redraw_frequency_millis = redraw_frequency_m...
def from_args ( cls , args = None , skip_dir_check = False ) : """Construct a Fetcher from given command line arguments . @ type args : list ( str ) @ param args : Command line arguments ( optional ) . Default is to use args from sys . argv @ type skip _ dir _ check : bool @ param skip _ dir _ check : Boole...
parser = argparse . ArgumentParser ( ) parser . set_defaults ( target = 'firefox' , build = 'latest' , tests = None ) # branch default is set after parsing target_group = parser . add_argument_group ( 'Target' ) target_group . add_argument ( '--target' , choices = sorted ( cls . TARGET_CHOICES ) , help = ( 'Specify the...
def _is_daemonset ( self , pod = None ) : """Determines if a K8sPod is part of a K8sDaemonSet . : param pod : The K8sPod we ' re interested in . : return : a boolean ."""
if 'kubernetes.io/created-by' in pod . annotations : parent = json . loads ( pod . annotations [ 'kubernetes.io/created-by' ] ) if parent [ 'reference' ] [ 'kind' ] == 'DaemonSet' : return True return False
def fingerprint_correlation ( T , obs1 , obs2 = None , tau = 1 , k = None , ncv = None ) : r"""Dynamical fingerprint for equilibrium correlation experiment . Parameters T : ( M , M ) ndarray or scipy . sparse matrix Transition matrix obs1 : ( M , ) ndarray Observable , represented as vector on state space...
# check if square matrix and remember size T = _types . ensure_ndarray_or_sparse ( T , ndim = 2 , uniform = True , kind = 'numeric' ) n = T . shape [ 0 ] # will not do fingerprint analysis for nonreversible matrices if not is_reversible ( T ) : raise ValueError ( 'Fingerprint calculation is not supported for nonrev...
def run ( create_application , settings = None , log_config = None ) : """Run a Tornado create _ application . : param create _ application : function to call to create a new application instance : param dict | None settings : optional configuration dictionary that will be passed through to ` ` create _ app...
from . import runner app_settings = { } if settings is None else settings . copy ( ) debug_mode = bool ( app_settings . get ( 'debug' , int ( os . environ . get ( 'DEBUG' , 0 ) ) != 0 ) ) app_settings [ 'debug' ] = debug_mode logging . config . dictConfig ( _get_logging_config ( debug_mode ) if log_config is None else ...
def get_tasks ( self , list_id , completed = False ) : '''Gets tasks for the list with the given ID , filtered by the given completion flag'''
return tasks_endpoint . get_tasks ( self , list_id , completed = completed )
def set_env ( self , arguments ) : """Setup the environment variables for the process ."""
return lib . zproc_set_env ( self . _as_parameter_ , byref ( zhash_p . from_param ( arguments ) ) )
def frommembers ( cls , members ) : """Series from iterable of member iterables ."""
return cls . frombitsets ( map ( cls . BitSet . frommembers , members ) )
def parse_pseudo_class ( self , sel , m , has_selector , iselector , is_html ) : """Parse pseudo class ."""
complex_pseudo = False pseudo = util . lower ( css_unescape ( m . group ( 'name' ) ) ) if m . group ( 'open' ) : complex_pseudo = True if complex_pseudo and pseudo in PSEUDO_COMPLEX : has_selector = self . parse_pseudo_open ( sel , pseudo , has_selector , iselector , m . end ( 0 ) ) elif not complex_pseudo and ...
def get_flux_biases_from_cache ( cur , chains , system_name , chain_strength , max_age = 3600 ) : """Determine the flux biases for all of the the given chains , system and chain strength . Args : cur ( : class : ` sqlite3 . Cursor ` ) : An sqlite3 cursor . This function is meant to be run within a : obj : ` w...
select = """ SELECT flux_bias FROM flux_bias_view WHERE chain_length = :chain_length AND nodes = :nodes AND chain_strength = :chain_strength AND system_name = :system_name AND insert_time >= :time_limit; """ encoded_data = {...
def from_logits ( behaviour_policy_logits , target_policy_logits , actions , discounts , rewards , values , bootstrap_value , clip_rho_threshold = 1.0 , clip_pg_rho_threshold = 1.0 , name = "vtrace_from_logits" ) : """multi _ from _ logits wrapper used only for tests"""
res = multi_from_logits ( [ behaviour_policy_logits ] , [ target_policy_logits ] , [ actions ] , discounts , rewards , values , bootstrap_value , clip_rho_threshold = clip_rho_threshold , clip_pg_rho_threshold = clip_pg_rho_threshold , name = name ) return VTraceFromLogitsReturns ( vs = res . vs , pg_advantages = res ....
def archive_path ( self , real_path ) : """Return the archive path for file with real _ path . Mapping is based on removal of self . path _ prefix which is determined by self . check _ files ( ) ."""
if ( not self . path_prefix ) : return ( real_path ) else : return ( os . path . relpath ( real_path , self . path_prefix ) )
def update_model_dict ( self ) : """Updates the model dictionary"""
dct = { } models = self . chimera . openModels for md in models . list ( ) : dct [ md . name ] = md . id self . model_dict = dct
def vb_xpcom_to_attribute_dict ( xpcom , interface_name = None , attributes = None , excluded_attributes = None , extra_attributes = None ) : '''Attempts to build a dict from an XPCOM object . Attributes that don ' t exist in the object return an empty string . attribute _ list = list of str or tuple ( str , < ...
# Check the interface if interface_name : m = re . search ( r'XPCOM.+implementing {0}' . format ( interface_name ) , six . text_type ( xpcom ) ) if not m : # TODO maybe raise error here ? log . warning ( 'Interface %s is unknown and cannot be converted to dict' , interface_name ) return dict ( )...
async def set_room_temperatures ( self , room_id , sleep_temp = None , comfort_temp = None , away_temp = None ) : """Set room temps ."""
if sleep_temp is None and comfort_temp is None and away_temp is None : return room = self . rooms . get ( room_id ) if room is None : _LOGGER . error ( "No such device" ) return room . sleep_temp = sleep_temp if sleep_temp else room . sleep_temp room . away_temp = away_temp if away_temp else room . away_tem...
def get_input_stream ( environ , safe_fallback = True ) : """Returns the input stream from the WSGI environment and wraps it in the most sensible way possible . The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length . . ....
stream = environ [ 'wsgi.input' ] content_length = get_content_length ( environ ) # A wsgi extension that tells us if the input is terminated . In # that case we return the stream unchanged as we know we can savely # read it until the end . if environ . get ( 'wsgi.input_terminated' ) : return stream # If we don ' ...
def __display_stats ( self ) : """Display some stats regarding unify process"""
self . display ( 'unify.tmpl' , processed = self . total , matched = self . matched , unified = self . total - self . matched )
def patch_namespaced_controller_revision ( self , name , namespace , body , ** kwargs ) : # noqa : E501 """patch _ namespaced _ controller _ revision # noqa : E501 partially update the specified ControllerRevision # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . patch_namespaced_controller_revision_with_http_info ( name , namespace , body , ** kwargs ) # noqa : E501 else : ( data ) = self . patch_namespaced_controller_revision_with_http_info ( name , namespace , body , ** kwa...
def transform ( self , maps ) : """This function transforms from component masses and caretsian spins to chi _ p . Parameters maps : a mapping object Examples Convert a dict of numpy . array : Returns out : dict A dict with key as parameter name and value as numpy . array or float of transformed v...
out = { } out [ "chi_p" ] = conversions . chi_p ( maps [ parameters . mass1 ] , maps [ parameters . mass2 ] , maps [ parameters . spin1x ] , maps [ parameters . spin1y ] , maps [ parameters . spin2x ] , maps [ parameters . spin2y ] ) return self . format_output ( maps , out )
def condense ( args ) : """% prog condense OM . bed Merge split alignments in OM bed ."""
from itertools import groupby from jcvi . assembly . patch import merge_ranges p = OptionParser ( condense . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bedfile , = args bed = Bed ( bedfile , sorted = False ) key = lambda x : ( x . seqid , x . start ,...
def add_r ( self , text = None ) : """Return a newly appended < a : r > element ."""
r = self . _add_r ( ) if text : r . t . text = text return r
def main ( ) : """main"""
args = MainArguments ( ) if args . tool . lower ( ) == "tool1" : args = Tool1Arguments ( ) elif args . tool . lower ( ) == "tool2" : args = Tool2Arguments ( ) else : print ( "Unknown tool" , args . tool ) print ( args )
def open_reader ( self , * args , ** kwargs ) : """Open the reader to read records from the result of the instance . If ` tunnel ` is ` True ` , instance tunnel will be used . Otherwise conventional routine will be used . If instance tunnel is not available and ` tunnel ` is not specified , , the method will fa...
use_tunnel = kwargs . get ( 'use_tunnel' , kwargs . get ( 'tunnel' ) ) auto_fallback_result = use_tunnel is None if use_tunnel is None : use_tunnel = options . tunnel . use_instance_tunnel result_fallback_errors = ( errors . InvalidProjectTable , errors . InvalidArgument ) if use_tunnel : # for compatibility if...
def show ( self ) : """Plot the result of the simulation once it ' s been intialized"""
from matplotlib import pyplot as plt if self . already_run : for ref in self . volts . keys ( ) : plt . plot ( self . t , self . volts [ ref ] , label = ref ) plt . title ( "Simulation voltage vs time" ) plt . legend ( ) plt . xlabel ( "Time [ms]" ) plt . ylabel ( "Voltage [m...
def _vax_to_ieee_single_float ( data ) : """Converts a float in Vax format to IEEE format . data should be a single string of chars that have been read in from a binary file . These will be processed 4 at a time into float values . Thus the total number of byte / chars in the string should be divisible by 4...
f = [ ] nfloat = int ( len ( data ) / 4 ) for i in range ( nfloat ) : byte2 = data [ 0 + i * 4 ] byte1 = data [ 1 + i * 4 ] byte4 = data [ 2 + i * 4 ] byte3 = data [ 3 + i * 4 ] # hex 0x80 = binary mask 100000 # hex 0x7f = binary mask 011111 sign = ( byte1 & 0x80 ) >> 7 expon = ( ( byte1...
def number_starts_with ( string : str ) -> bool : """Determine if a particular string begins with a specific number . Args : string : A string which we are checking Returns : A boolean value indicating whether the string starts with ' 5' Examples : > > > number _ starts _ with ( ' 5-2345861 ' ) True ...
import re pattern = re . compile ( '^5' ) if pattern . match ( string ) : return True return False
def add_name_variant ( self , name ) : """Add name variant . Args : : param name : name variant for the current author . : type name : string"""
self . _ensure_field ( 'name' , { } ) self . obj [ 'name' ] . setdefault ( 'name_variants' , [ ] ) . append ( name )
def init_UI ( self ) : """Builds User Interface for the interpretation Editor"""
# set fonts FONT_WEIGHT = 1 if sys . platform . startswith ( 'win' ) : FONT_WEIGHT = - 1 font1 = wx . Font ( 9 + FONT_WEIGHT , wx . SWISS , wx . NORMAL , wx . NORMAL , False , self . font_type ) font2 = wx . Font ( 12 + FONT_WEIGHT , wx . SWISS , wx . NORMAL , wx . NORMAL , False , self . font_type ) # if you ' re ...
def nearest_multiple ( number , divisor ) : """This function rounds the input number to the closest multiple of a specified number . Parameters : number : The number to be rounded . divisor : The number whose multiple is used for rounding . Returns : int : The rounded number . Examples : > > > nearest...
lower = ( number // divisor ) * divisor upper = lower + divisor if ( number - lower ) > ( upper - number ) : return upper else : return lower
def emulate_repeat ( self , value , timeval ) : """The repeat press of a key / mouse button , e . g . double click ."""
repeat_event = self . create_event_object ( "Repeat" , 2 , value , timeval ) return repeat_event
def get_service_from_display_name ( displayName ) : """Get the service unique name given its display name . @ see : L { get _ service } @ type displayName : str @ param displayName : Service display name . You can get this value from the C { DisplayName } member of the service descriptors returned by L { ...
with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager : return win32 . GetServiceKeyName ( hSCManager , displayName )
def remove ( self , key ) : '''remove key from the namespace . it is fine to remove a key multiple times .'''
encodedKey = json . dumps ( key ) sql = 'DELETE FROM ' + self . table + ' WHERE name = %s' with self . connect ( ) as conn : with doTransaction ( conn ) : return executeSQL ( conn , sql , args = [ encodedKey ] )
def calculate_imf_steadiness ( inst , steady_window = 15 , min_window_frac = 0.75 , max_clock_angle_std = 90.0 / np . pi , max_bmag_cv = 0.5 ) : """Calculate IMF steadiness using clock angle standard deviation and the coefficient of variation of the IMF magnitude in the GSM Y - Z plane Parameters inst : pysat...
# We are not going to interpolate through missing values sample_rate = int ( inst . tag [ 0 ] ) max_wnum = np . floor ( steady_window / sample_rate ) if max_wnum != steady_window / sample_rate : steady_window = max_wnum * sample_rate print ( "WARNING: sample rate is not a factor of the statistical window" ) ...
def image ( self ) : """Generates the image using self . genImage ( ) , then rotates it to self . direction and returns it ."""
self . _image = self . genImage ( ) self . _image = funcs . rotateImage ( self . _image , self . direction ) return self . _image
def sum ( self , axis = None , dtype = None , out = None , keepdims = False ) : """Return the sum of ` ` self ` ` . See Also numpy . sum prod"""
return self . elem . __array_ufunc__ ( np . add , 'reduce' , self . elem , axis = axis , dtype = dtype , out = ( out , ) , keepdims = keepdims )