signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _parse ( batch_cmd ) : """: rtype : ( sh _ cmd , batch _ to _ file _ s , batch _ from _ file ) : returns : parsed result like below : . . code - block : : python # when parsing ' diff IN _ BATCH0 IN _ BATCH1 > OUT _ BATCH ' ' diff / tmp / relshell - AbCDeF / tmp / relshell - uVwXyz ' , ( < instance of...
cmd_array = shlex . split ( batch_cmd ) ( cmd_array , batch_to_file_s ) = BatchCommand . _parse_in_batches ( cmd_array ) ( cmd_array , batch_from_file ) = BatchCommand . _parse_out_batch ( cmd_array ) return ( list2cmdline ( cmd_array ) , batch_to_file_s , batch_from_file )
def baseDomain ( domain , includeScheme = True ) : """Return only the network location portion of the given domain unless includeScheme is True"""
result = '' url = urlparse ( domain ) if includeScheme : result = '%s://' % url . scheme if len ( url . netloc ) == 0 : result += url . path else : result += url . netloc return result
def _check_sensor_platform_consistency ( self , sensor ) : """Make sure sensor and platform are consistent Args : sensor ( str ) : Sensor name from YAML dataset definition Raises : ValueError if they don ' t match"""
ref_sensor = SENSORS . get ( self . platform , None ) if ref_sensor and not sensor == ref_sensor : logger . error ( 'Sensor-Platform mismatch: {} is not a payload ' 'of {}. Did you choose the correct reader?' . format ( sensor , self . platform ) )
def main ( ) : """main function"""
parser = argparse . ArgumentParser ( description = 'Github within the Command Line' ) group = parser . add_mutually_exclusive_group ( ) group . add_argument ( '-n' , '--url' , type = str , help = "Get repos from the user profile's URL" ) group . add_argument ( '-r' , '--recursive' , type = str , help = "Get the file st...
def get_picture ( self , login = None , ** kwargs ) : """Get a user ' s picture . : param str login : Login of the user to check : return : JSON"""
_login = kwargs . get ( 'login' , login or self . _login ) _activities_url = PICTURE_URL . format ( login = _login ) return self . _request_api ( url = _activities_url ) . content
def frameify ( self , state , data ) : """Yield chunk data as a single frame , and buffer the rest ."""
# If we ' ve pulled in all the chunk data , buffer the data if state . chunk_remaining <= 0 : state . recv_buf += data return # Pull in any partially - processed data data = state . recv_buf + data # Determine how much belongs to the chunk if len ( data ) <= state . chunk_remaining : chunk = data data =...
def move ( self , new_path , replication = None ) : """Move current path to a new location . : param new _ path : target location of current file / directory : param replication : number of replication"""
if not new_path . startswith ( '/' ) : new_path = self . _normpath ( self . dirname + '/' + new_path ) else : new_path = self . _normpath ( new_path ) if new_path == self . path : raise ValueError ( 'New path should be different from the original one.' ) update_def = self . UpdateRequestXML ( path = new_pat...
def _extract_from_object ( self , selector ) : """Extracts all values from ` self . obj ` object addressed with a ` selector ` . Selector can be a ` ` slice ` ` , or a singular value extractor in form of a valid dictionary key ( hashable object ) . Object ( operated on ) can be anything with an itemgetter or ...
if isinstance ( selector , slice ) : # we must expand the slice manually , in order to be able to apply to # for example , to mapping types , or general objects # ( e . g . slice ` 4 : : 2 ` will filter all even numerical keys / attrs > = 4) start = selector . start or 0 step = selector . step or 1 if selec...
def publish ( self , key , data ) : '''Publishes the data to the event stream .'''
publish_data = { key : data } pub = salt . utils . json . dumps ( publish_data ) + str ( '\n\n' ) # future lint : disable = blacklisted - function self . handler . write_message ( pub )
def get_initial ( self ) : """Returns the initial data to use for forms on this view ."""
initial = super ( ProjectCopy , self ) . get_initial ( ) if self . copy_object : initial . update ( { 'name' : '%s copy' % self . copy_object . name , 'description' : self . copy_object . description , 'use_repo_fabfile' : self . copy_object . use_repo_fabfile , 'fabfile_requirements' : self . copy_object . fabfile...
def get_workspaces ( self ) : """Get a list of workspaces . Returns JSON - like data , not a Con instance . You might want to try the : meth : ` Con . workspaces ` instead if the info contained here is too little . : rtype : List of : class : ` WorkspaceReply ` ."""
data = self . message ( MessageType . GET_WORKSPACES , '' ) return json . loads ( data , object_hook = WorkspaceReply )
def choose_key ( gpg_private_keys ) : """Displays gpg key choice and returns key"""
uid_strings_fp = [ ] uid_string_fp2key = { } current_key_index = None for i , key in enumerate ( gpg_private_keys ) : fingerprint = key [ 'fingerprint' ] if fingerprint == config [ "gpg_key_fingerprint" ] : current_key_index = i for uid_string in key [ 'uids' ] : uid_string_fp = '"' + uid_st...
async def section ( self , sec = None ) : """Section / dict serialization : return :"""
if self . writing : await dump_varint ( self . iobj , len ( sec ) ) for key in sec : await self . section_name ( key ) await self . storage_entry ( sec [ key ] ) else : sec = { } if sec is None else sec count = await load_varint ( self . iobj ) for idx in range ( count ) : se...
def _set_network_options ( self ) : """Set up VMware networking ."""
# first some sanity checks for adapter_number in range ( 0 , self . _adapters ) : # we want the vmnet interface to be connected when starting the VM connected = "ethernet{}.startConnected" . format ( adapter_number ) if self . _get_vmx_setting ( connected ) : del self . _vmx_pairs [ connected ] # then c...
def add_url ( self , url , line = 0 , column = 0 , page = 0 , name = u"" , base = None ) : """If a local webroot directory is configured , replace absolute URLs with it . After that queue the URL data for checking ."""
webroot = self . aggregate . config [ "localwebroot" ] if webroot and url and url . startswith ( u"/" ) : url = webroot + url [ 1 : ] log . debug ( LOG_CHECK , "Applied local webroot `%s' to `%s'." , webroot , url ) super ( FileUrl , self ) . add_url ( url , line = line , column = column , page = page , name = ...
def _connect_syndic ( self , opts ) : '''Create a syndic , and asynchronously connect it to a master'''
auth_wait = opts [ 'acceptance_wait_time' ] failed = False while True : if failed : if auth_wait < self . max_auth_wait : auth_wait += self . auth_wait log . debug ( "sleeping before reconnect attempt to %s [%d/%d]" , opts [ 'master' ] , auth_wait , self . max_auth_wait , ) yield...
def execute_command ( command ) : """Execute a command and return its output"""
command = shlex . split ( command ) try : process = subprocess . Popen ( command , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) except FileNotFoundError : raise RuntimeError ( "Command not found: {}" . format ( repr ( command ) ) ) process . wait ( ) # TODO : may use a...
def cases ( self ) : """All test cases created by the user"""
import nitrate if self . _cases is None : log . info ( u"Searching for cases created by {0}" . format ( self . user ) ) self . _cases = [ case for case in nitrate . TestCase . search ( author__email = self . user . email , create_date__gt = str ( self . options . since ) , create_date__lt = str ( self . options...
def _save ( self , fn ) : """Persist the notebook to the given file . : param fn : the file name"""
# create JSON object j = json . dumps ( { 'description' : self . description ( ) , 'pending' : self . _pending , 'results' : self . _results } , indent = 4 , cls = MetadataEncoder ) # write to file with open ( fn , 'w' ) as f : f . write ( j )
def delete_table_rate_rule_by_id ( cls , table_rate_rule_id , ** kwargs ) : """Delete TableRateRule Delete an instance of TableRateRule by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . delete _ table _ ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _delete_table_rate_rule_by_id_with_http_info ( table_rate_rule_id , ** kwargs ) else : ( data ) = cls . _delete_table_rate_rule_by_id_with_http_info ( table_rate_rule_id , ** kwargs ) return data
def _clearQuantities ( self ) : """Computes the cleared quantities for each offer / bid according to the dispatched output from the OPF solution ."""
generators = [ g for g in self . case . generators if not g . is_load ] vLoads = [ g for g in self . case . generators if g . is_load ] for g in generators : self . _clearQuantity ( self . offers , g ) for vl in vLoads : self . _clearQuantity ( self . bids , vl )
def main ( ) : """NAME odp _ srm _ magic . py DESCRIPTION converts ODP measurement format files to magic _ measurements format files SYNTAX odp _ srm _ magic . py [ command line options ] OPTIONS - h : prints the help message and quits . - F FILE : specify output measurements file , default is magic...
version_num = pmag . get_version ( ) meas_file = 'magic_measurements.txt' samp_file = 'er_samples.txt' ErSpecs , ErSamps , ErSites , ErLocs , ErCits = [ ] , [ ] , [ ] , [ ] , [ ] MagRecs = [ ] citation = "This study" dir_path , demag = '.' , 'NRM' args = sys . argv noave = 0 , if '-WD' in args : ind = args . index ...
def acceptCompletion ( self ) : """Accepts the current completion and inserts the code into the edit . : return < bool > accepted"""
tree = self . _completerTree if not tree : return False tree . hide ( ) item = tree . currentItem ( ) if not item : return False # clear the previously typed code for the block cursor = self . textCursor ( ) text = cursor . block ( ) . text ( ) col = cursor . columnNumber ( ) end = col while col : col -= 1 ...
def from_unix ( cls , seconds , milliseconds = 0 ) : """Produce a full | datetime . datetime | object from a Unix timestamp"""
base = list ( time . gmtime ( seconds ) ) [ 0 : 6 ] base . append ( milliseconds * 1000 ) # microseconds return cls ( * base )
def prepare_value_for_storage ( self , value , pk ) : """Prepare the value to be stored in the zset We ' ll store the value and pk concatenated . For the parameters , see BaseRangeIndex . prepare _ value _ for _ storage"""
value = super ( TextRangeIndex , self ) . prepare_value_for_storage ( value , pk ) return self . separator . join ( [ value , str ( pk ) ] )
def _extract_lengths ( ll ) : """Extract list of possible lengths from string"""
results = set ( ) if ll is None : return [ ] for val in ll . split ( ',' ) : m = _NUM_RE . match ( val ) if m : results . add ( int ( val ) ) else : m = _RANGE_RE . match ( val ) if m is None : raise Exception ( "Unrecognized length specification %s" % ll ) mi...
def import_locations ( self , data ) : """Parse geonames . org country database exports . ` ` import _ locations ( ) ` ` returns a list of : class : ` trigpoints . Trigpoint ` objects generated from the data exported by geonames . org _ . It expects data files in the following tab separated format : : 26334...
self . _data = data field_names = ( 'geonameid' , 'name' , 'asciiname' , 'alt_names' , 'latitude' , 'longitude' , 'feature_class' , 'feature_code' , 'country' , 'alt_country' , 'admin1' , 'admin2' , 'admin3' , 'admin4' , 'population' , 'altitude' , 'gtopo30' , 'tzname' , 'modified_date' ) comma_split = lambda s : s . s...
def parse_toc ( html_content ) : """Parse TOC of HTML content if the SHOW _ TOC config is true . : param html _ content : raw HTML content : return : tuple ( processed HTML , toc list , toc HTML unordered list )"""
from flask import current_app from veripress . model . toc import HtmlTocParser if current_app . config [ 'SHOW_TOC' ] : toc_parser = HtmlTocParser ( ) toc_parser . feed ( html_content ) toc_html = toc_parser . toc_html ( depth = current_app . config [ 'TOC_DEPTH' ] , lowest_level = current_app . config [ '...
def _match_pyephem_snapshot_to_atlas_exposures ( self , pyephemDB , exposures , mjd ) : """* match pyephem snapshot to atlas exposures * * * Key Arguments : * * - ` ` pyephemDB ` ` - - the pyephem solar - system snapshot database - ` ` exposures ` ` - - the atlas exposures to match against the snapshot - ` ...
self . log . info ( 'starting the ``_match_pyephem_snapshot_to_atlas_exposures`` method' ) global DEG_TO_RAD_FACTOR global RAD_TO_DEG_FACTOR global moversDict e = len ( exposures ) print "Matching %(e)s ATLAS exposures against the pyephem snapshot for MJD = %(mjd)s" % locals ( ) # MAKE SURE HEALPIX SMALL ENOUGH TO MATC...
def _get_acorn ( self , method , * items ) : """Gets either a slice or an item from an array . Used for the _ _ getitem _ _ and _ _ getslice _ _ special methods of the sub - classed array . Args : method ( str ) : on of [ ' slice ' , ' item ' ] ."""
# IMPORTANT ! ! I lost two hours because the ndarray becomes unstable if you # don ' t call the original method first . Somehow passing the array instance to # other methods changed its internal representation and made it unusable by # the original numpy functions . Putting them first makes it work . # Because we had t...
def generate ( self , z_mu = None ) : """Generate data by sampling from latent space . If z _ mu is not None , data for this point in latent space is generated . Otherwise , z _ mu is drawn from prior in latent space ."""
if z_mu is None : z_mu = np . random . normal ( size = self . network_architecture [ "n_z" ] ) # Note : This maps to mean of distribution , we could alternatively # sample from Gaussian distribution return self . sess . run ( self . x_reconstr_mean , feed_dict = { self . z : z_mu } )
def text_log_errors ( self , request , project , pk = None ) : """Gets a list of steps associated with this job"""
try : job = Job . objects . get ( repository__name = project , id = pk ) except Job . DoesNotExist : return Response ( "No job with id: {0}" . format ( pk ) , status = HTTP_404_NOT_FOUND ) textlog_errors = ( TextLogError . objects . filter ( step__job = job ) . select_related ( "_metadata" , "_metadata__failure...
def card_bundler ( provider : Provider , deck : Deck , tx : dict ) -> CardBundle : '''each blockchain transaction can contain multiple cards , wrapped in bundles . This method finds and returns those bundles .'''
return CardBundle ( deck = deck , blockhash = tx [ 'blockhash' ] , txid = tx [ 'txid' ] , timestamp = tx [ 'time' ] , blockseq = tx_serialization_order ( provider , tx [ "blockhash" ] , tx [ "txid" ] ) , blocknum = provider . getblock ( tx [ "blockhash" ] ) [ "height" ] , sender = find_tx_sender ( provider , tx ) , vou...
def get_instance_property ( instance , property_name ) : """Retrieves property of an instance , keeps retrying until getting a non - None"""
name = get_name ( instance ) while True : try : value = getattr ( instance , property_name ) if value is not None : break print ( f"retrieving {property_name} on {name} produced None, retrying" ) time . sleep ( RETRY_INTERVAL_SEC ) instance . reload ( ) co...
def apply_rectwv_coeff ( reduced_image , rectwv_coeff , args_resampling = 2 , args_ignore_dtu_configuration = True , debugplot = 0 ) : """Compute rectification and wavelength calibration coefficients . Parameters reduced _ image : HDUList object Image with preliminary basic reduction : bpm , bias , dark and ...
logger = logging . getLogger ( __name__ ) # header and data array ( use deepcopy to avoid modifying # reduced _ image [ 0 ] . header as a side effect ) header = copy . deepcopy ( reduced_image [ 0 ] . header ) image2d = reduced_image [ 0 ] . data # apply global offsets image2d = apply_integer_offsets ( image2d = image2...
def set_object ( self , object , logmsg = None ) : # @ ReservedAssignment """Special version which checks if the head - log needs an update as well : return : self"""
oldbinsha = None if logmsg is not None : head = self . repo . head if not head . is_detached and head . ref == self : oldbinsha = self . commit . binsha # END handle commit retrieval # END handle message is set super ( Reference , self ) . set_object ( object , logmsg ) if oldbinsha is not None : # ...
def Run ( self ) : """Event loop ."""
if data_store . RelationalDBEnabled ( ) : data_store . REL_DB . RegisterMessageHandler ( self . _ProcessMessageHandlerRequests , self . well_known_flow_lease_time , limit = 100 ) data_store . REL_DB . RegisterFlowProcessingHandler ( self . ProcessFlow ) try : while 1 : processed = self . RunOnce ( )...
def get_key ( self , key , request_only = False ) : """Get a data key value for each resolved package . Args : key ( str ) : String key of property , eg ' tools ' . request _ only ( bool ) : If True , only return the key from resolved packages that were also present in the request . Returns : Dict of { ...
values = { } requested_names = [ x . name for x in self . _package_requests if not x . conflict ] for pkg in self . resolved_packages : if ( not request_only ) or ( pkg . name in requested_names ) : value = getattr ( pkg , key ) if value is not None : values [ pkg . name ] = ( pkg , valu...
def change_directory ( path = None ) : """Context manager that changes directory and resets it when existing > > > with change _ directory ( ' / tmp ' ) : > > > pass"""
if path is not None : try : oldpwd = getcwd ( ) logger . debug ( 'changing directory from %s to %s' % ( oldpwd , path ) ) chdir ( path ) yield finally : chdir ( oldpwd ) else : yield
def _get_request ( self , auth = None ) : '''Return an http request object auth : Auth data to use Returns : A HSRequest object'''
self . request = HSRequest ( auth or self . auth , self . env ) self . request . response_callback = self . response_callback return self . request
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'age' ) and self . age is not None : _dict [ 'age' ] = self . age . _to_dict ( ) if hasattr ( self , 'gender' ) and self . gender is not None : _dict [ 'gender' ] = self . gender . _to_dict ( ) if hasattr ( self , 'face_location' ) and self . face_location is not None : _dict...
def get_command ( self , command_input , docker_object = None , buffer = None , size = None ) : """return command instance which is the actual command to be executed : param command _ input : str , command name and its args : " command arg arg2 = val opt " : param docker _ object : : param buffer : : param ...
logger . debug ( "get command for command input %r" , command_input ) if not command_input : # noop , don ' t do anything return if command_input [ 0 ] in [ "/" ] : # we could add here ! , @ , . . . command_name = command_input [ 0 ] unparsed_command_args = shlex . split ( command_input [ 1 : ] ) else : ...
def verify_constraints ( constraints ) : """Verify values returned from : meth : ` make _ constraints ` . Used internally during the : meth : ` build ` process . : param constraints : value returned from : meth : ` make _ constraints ` : type constraints : : class : ` list ` : raises ValueError : if verific...
# verify return is a list if not isinstance ( constraints , list ) : raise ValueError ( "invalid type returned by make_constraints: %r (must be a list)" % constraints ) # verify each list element is a Constraint instance for constraint in constraints : if not isinstance ( constraint , Constraint ) : rai...
def _complete_parsers_with_converters ( self , parser , parser_supported_type , desired_type , matching_c_generic_to_type , matching_c_approx_to_type , matching_c_exact_to_type ) : """Internal method to create parsing chains made of a parser and converters from the provided lists . Once again a JOKER for a type m...
matching_p_generic , matching_p_generic_with_approx_chain , matching_p_approx , matching_p_approx_with_approx_chain , matching_p_exact , matching_p_exact_with_approx_chain = [ ] , [ ] , [ ] , [ ] , [ ] , [ ] # resolve Union and TypeVar desired_types = get_alternate_types_resolving_forwardref_union_and_typevar ( desired...
def register_action ( * args , ** kwarg ) : '''Decorator for an action , the arguments order is not relevant , but it ' s best to use the same order as in the docopt for clarity .'''
def decorator ( fun ) : KeywordArgumentParser . _action_dict [ frozenset ( args ) ] = fun return fun return decorator
async def _location_auth_protect ( self , location ) : '''Checks to see if the new location is 1 . The same top level domain 2 . As or more secure than the current connection type Returns : True ( bool ) : If the current top level domain is the same and the connection type is equally or more secure . Fa...
netloc_sans_port = self . host . split ( ':' ) [ 0 ] netloc_sans_port = netloc_sans_port . replace ( ( re . match ( _WWX_MATCH , netloc_sans_port ) [ 0 ] ) , '' ) base_domain = '.' . join ( netloc_sans_port . split ( '.' ) [ - 2 : ] ) l_scheme , l_netloc , _ , _ , _ , _ = urlparse ( location ) location_sans_port = l_ne...
def get_targets ( self ) : """Sets targets ."""
if self . xml_root . tag == "testcases" : self . submit_target = self . config . get ( "testcase_taget" ) self . queue_url = self . config . get ( "testcase_queue" ) self . log_url = self . config . get ( "testcase_log" ) elif self . xml_root . tag == "testsuites" : self . submit_target = self . config ...
def parse_session_cookie ( cookie_to_cook ) : """cookie _ to _ cook = http _ header [ ' cookie ' ]"""
# print ( " cookie _ to _ cook : % s " % str ( cookie _ to _ cook ) ) session_value = None tokens = cookie_to_cook . split ( ";" ) for tok in tokens : if 'remi_session=' in tok : # print ( " found session id : % s " % str ( tok ) ) try : session_value = int ( tok . replace ( 'remi_session=' , ''...
def delete_node_1ton ( node_list , begin , node , end ) : # type : ( [ ] , LinkedNode , LinkedNode , LinkedNode ) - > [ ] """delete the node which has 1 - input and n - output"""
if end is None : assert end is not None end = node . successor elif not isinstance ( end , list ) : end = [ end ] if any ( e_ . in_or_out for e_ in end ) : # if the end is output node , the output name will be kept to avoid the model output name updating . begin . out_redirect ( node . single_input , no...
def changes ( self ) : """Collects all changes that have been performed on the monitored path , returning them as a ( created , deleted ) tuple ."""
deleted = [ ] for path in list ( self . files ) : isdir = path . endswith ( os . sep ) abspath = os . path . join ( self . path , path ) try : is_deleted = ( not os . path . exists ( abspath ) or # actually deleted os . path . isdir ( abspath ) != isdir # changed from / to folder ) ...
def close ( self ) : """Release all resources associated with this factory ."""
if self . mdr is None : return exc = ( None , None , None ) try : self . cursor . close ( ) except : exc = sys . exc_info ( ) try : if self . mdr . __exit__ ( * exc ) : exc = ( None , None , None ) except : exc = sys . exc_info ( ) self . mdr = None self . cursor = None if exc != ( None , No...
def _get_component ( self , string , initial_pos ) : '''given a string and a position , return both an updated position and either a Component Object or a String back to the caller'''
add_code = string [ initial_pos : initial_pos + self . ADDR_CODE_LENGTH ] if add_code == 'REM' : raise ish_reportException ( "This is a remarks record" ) if add_code == 'EQD' : raise ish_reportException ( "This is EQD record" ) initial_pos += self . ADDR_CODE_LENGTH try : useable_map = self . MAP [ add_code...
def build_url ( self ) : """Only logs that this URL is unknown ."""
super ( UnknownUrl , self ) . build_url ( ) if self . is_ignored ( ) : self . add_info ( _ ( "%(scheme)s URL ignored." ) % { "scheme" : self . scheme . capitalize ( ) } ) self . set_result ( _ ( "ignored" ) ) else : self . set_result ( _ ( "URL is unrecognized or has invalid syntax" ) , valid = False )
def raise_for_old_graph ( graph ) : """Raise an ImportVersionWarning if the BEL graph was produced by a legacy version of PyBEL . : raises ImportVersionWarning : If the BEL graph was produced by a legacy version of PyBEL"""
graph_version = tokenize_version ( graph . pybel_version ) if graph_version < PYBEL_MINIMUM_IMPORT_VERSION : raise ImportVersionWarning ( graph_version , PYBEL_MINIMUM_IMPORT_VERSION )
def grow ( self ) : "Add another worker to the pool ."
t = self . worker_factory ( self ) t . start ( ) self . _size += 1
def reset ( self ) : "Reset the internal memory ."
self . hidden = [ next ( self . parameters ( ) ) . data . new ( 0 ) for i in range ( self . n_layers + 1 ) ]
def p_inheritance ( self , p ) : """inheritance : EXTENDS type _ ref | empty"""
if p [ 1 ] : if p [ 2 ] . nullable : msg = 'Reference cannot be nullable.' self . errors . append ( ( msg , p . lineno ( 1 ) , self . path ) ) else : p [ 0 ] = p [ 2 ]
def png_segno ( data = 'QR Code Symbol' ) : """Segno PNG"""
segno . make_qr ( data , error = 'm' ) . save ( 'out/segno_%s.png' % data , scale = 10 , addad = False )
def _lpad ( self , length , pad = ' ' ) : """Returns string of given length by truncating ( on right ) or padding ( on left ) original string Parameters length : int pad : string , default is ' ' Examples > > > import ibis > > > table = ibis . table ( [ ( ' strings ' , ' string ' ) ] ) > > > expr = ...
return ops . LPad ( self , length , pad ) . to_expr ( )
def block_anyfilter ( parser , token ) : """Turn any template filter into a blocktag . Usage : : { % load libs _ tags % } { % block _ anyfilter django . template . defaultfilters . truncatewords _ html 15 % } / / Something complex that generates html output { % endblockanyfilter % }"""
bits = token . contents . split ( ) nodelist = parser . parse ( ( 'endblockanyfilter' , ) ) parser . delete_first_token ( ) return BlockAnyFilterNode ( nodelist , bits [ 1 ] , * bits [ 2 : ] )
def seconds_until_renew ( self ) : """Returns the number of seconds between the current time and the set renew time . It can be negative if the leader election is running late ."""
delta = self . renew_time - datetime . now ( self . renew_time . tzinfo ) return delta . total_seconds ( )
def wrap_arguments ( args = None ) : """Wrap a list of tuples in xml ready to pass into a SOAP request . Args : args ( list ) : a list of ( name , value ) tuples specifying the name of each argument and its value , eg ` ` [ ( ' InstanceID ' , 0 ) , ( ' Speed ' , 1 ) ] ` ` . The value can be a string or so...
if args is None : args = [ ] tags = [ ] for name , value in args : tag = "<{name}>{value}</{name}>" . format ( name = name , value = escape ( "%s" % value , { '"' : "&quot;" } ) ) # % converts to unicode because we are using unicode literals . # Avoids use of ' unicode ' function which does not exist in...
def _compute_f1 ( self , C , mag , rrup ) : """Compute f1 term ( eq . 4 , page 105)"""
r = np . sqrt ( rrup ** 2 + C [ 'c4' ] ** 2 ) f1 = ( C [ 'a1' ] + C [ 'a12' ] * ( 8.5 - mag ) ** C [ 'n' ] + ( C [ 'a3' ] + C [ 'a13' ] * ( mag - C [ 'c1' ] ) ) * np . log ( r ) ) if mag <= C [ 'c1' ] : f1 += C [ 'a2' ] * ( mag - C [ 'c1' ] ) else : f1 += C [ 'a4' ] * ( mag - C [ 'c1' ] ) return f1
def keep ( self , diff ) : """Mark this diff ( or volume ) to be kept in path ."""
path = self . extraKeys [ diff ] if not path . startswith ( "/" ) : logger . debug ( "Keeping %s" , path ) del self . extraKeys [ diff ] return # Copy into self . userPath , if not there already keyName = self . _keyName ( diff . toUUID , diff . fromUUID , path ) newPath = os . path . join ( self . userPath...
def elapsed ( t0 = 0.0 ) : """get elapsed time from the give time Returns : now : the absolute time now dt _ str : elapsed time in string"""
now = time ( ) dt = now - t0 dt_sec = Decimal ( str ( dt ) ) . quantize ( Decimal ( '.0001' ) , rounding = ROUND_DOWN ) if dt_sec <= 1 : dt_str = str ( dt_sec ) + ' second' else : dt_str = str ( dt_sec ) + ' seconds' return now , dt_str
def wiki_download ( url ) : '''scrape friendly : sleep 20 seconds between each request , cache each result .'''
DOWNLOAD_TMPL = '../data/tv_and_movie_freqlist%s.html' freq_range = url [ url . rindex ( '/' ) + 1 : ] tmp_path = DOWNLOAD_TMPL % freq_range if os . path . exists ( tmp_path ) : print ( 'cached.......' , url ) with codecs . open ( tmp_path , 'r' , 'utf8' ) as f : return f . read ( ) , True with codecs ....
def maps_json ( ) : """Generates a json object which serves as bridge between the web interface and the map source collection . All attributes relevant for openlayers are converted into JSON and served through this route . Returns : Response : All map sources as JSON object ."""
map_sources = { id : { "id" : map_source . id , "name" : map_source . name , "folder" : map_source . folder , "min_zoom" : map_source . min_zoom , "max_zoom" : map_source . max_zoom , "layers" : [ { "min_zoom" : layer . min_zoom , "max_zoom" : layer . max_zoom , "tile_url" : layer . tile_url . replace ( "$" , "" ) , } ...
def rsa_decrypt ( encrypted_data , pem , password = None ) : """rsa 解密 : param encrypted _ data : 待解密 bytes : param pem : RSA private key 内容 / binary : param password : RSA private key pass phrase : return : 解密后的 binary"""
from cryptography . hazmat . backends import default_backend from cryptography . hazmat . primitives import serialization from cryptography . hazmat . primitives import hashes from cryptography . hazmat . primitives . asymmetric import padding encrypted_data = to_binary ( encrypted_data ) pem = to_binary ( pem ) privat...
def __op ( name , val , fmt = None , const = False , consume = 0 , produce = 0 ) : """provides sensible defaults for a code , and registers it with the _ _ OPTABLE for lookup ."""
name = name . lower ( ) # fmt can either be a str representing the struct to unpack , or a # callable to do more complex unpacking . If it ' s a str , create a # callable for it . if isinstance ( fmt , str ) : fmt = partial ( _unpack , compile_struct ( fmt ) ) operand = ( name , val , fmt , consume , produce , cons...
def to_dataframe ( self ) : """Build a dataframe from the effect collection"""
# list of properties to extract from Variant objects if they ' re # not None variant_properties = [ "contig" , "start" , "ref" , "alt" , "is_snv" , "is_transversion" , "is_transition" ] def row_from_effect ( effect ) : row = OrderedDict ( ) row [ 'variant' ] = str ( effect . variant . short_description ) fo...
def _input_as_multiline_string ( self , data ) : """Write multiline string to temp file , return filename data : a multiline string to be written to a file ."""
self . _input_filename = self . getTmpFilename ( self . WorkingDir , suffix = '.fasta' ) with open ( self . _input_filename , 'w' ) as f : f . write ( data ) return self . _input_filename
def codegen ( lang , # type : str i , # type : List [ Dict [ Text , Any ] ] schema_metadata , # type : Dict [ Text , Any ] loader # type : Loader ) : # type : ( . . . ) - > None """Generate classes with loaders for the given Schema Salad description ."""
j = schema . extend_and_specialize ( i , loader ) gen = None # type : Optional [ CodeGenBase ] if lang == "python" : gen = PythonCodeGen ( sys . stdout ) elif lang == "java" : gen = JavaCodeGen ( schema_metadata . get ( "$base" , schema_metadata . get ( "id" ) ) ) else : raise Exception ( "Unsupported code ...
def _read_header ( filename ) : """Read the text header for each file Parameters channel _ file : Path path to single filename with the header Returns dict header"""
with filename . open ( 'rb' ) as f : h = f . read ( HDR_LENGTH ) . decode ( ) header = { } for line in h . split ( '\n' ) : if '=' in line : key , value = line . split ( ' = ' ) key = key . strip ( ) [ 7 : ] value = value . strip ( ) [ : - 1 ] header [...
def margin_to_exchange ( self , symbol , currency , amount ) : """借贷账户划出至现货账户 : param amount : : param currency : : param symbol : : return :"""
params = { 'symbol' : symbol , 'currency' : currency , 'amount' : amount } path = '/v1/dw/transfer-out/margin' def _wrapper ( _func ) : @ wraps ( _func ) def handle ( ) : _func ( api_key_post ( params , path ) ) return handle return _wrapper
def get_cheapest_quotes ( self , ** params ) : """{ API _ HOST } / apiservices / browsequotes / v1.0 / { market } / { currency } / { locale } / { originPlace } / { destinationPlace } / { outboundPartialDate } / { inboundPartialDate } ? apiKey = { apiKey }"""
service_url = "{url}/{params_path}" . format ( url = self . BROWSE_QUOTES_SERVICE_URL , params_path = self . _construct_params ( params , self . _REQ_PARAMS , self . _OPT_PARAMS ) ) return self . make_request ( service_url , headers = self . _headers ( ) , ** params )
async def disable ( self , service , * , reason = None ) : """Enters maintenance mode for service Parameters : service ( ObjectID ) : Service ID reason ( str ) : Text string explaining the reason for placing the service into maintenance mode . Returns : bool : ` ` True ` ` on success Places a given se...
return await self . maintenance ( service , False , reason = reason )
def delete_router ( self , router ) : '''Delete the specified router'''
router_id = self . _find_router_id ( router ) ret = self . network_conn . delete_router ( router = router_id ) return ret if ret else True
def get_json_content ( file_path ) : """Load json file content Parameters file _ path : path to the file Raises TypeError Error with the file path"""
try : with open ( file_path , 'r' ) as file : return json . load ( file ) except TypeError as err : print ( 'Error: ' , err ) return None
def _load_nucmer_hits ( self , infile ) : '''Returns dict ref name = > list of nucmer hits from infile'''
hits = { } file_reader = pymummer . coords_file . reader ( infile ) for al in file_reader : if al . ref_name not in hits : hits [ al . ref_name ] = [ ] hits [ al . ref_name ] . append ( al ) return hits
def register_user ( self , user , allow_login = None , send_email = None , _force_login_without_confirmation = False ) : """Service method to register a user . Sends signal ` user _ registered ` . Returns True if the user has been logged in , False otherwise ."""
should_login_user = ( not self . security . confirmable or self . security . login_without_confirmation or _force_login_without_confirmation ) should_login_user = ( should_login_user if allow_login is None else allow_login and should_login_user ) if should_login_user : user . active = True # confirmation token depe...
def to_csv ( self , dest : str ) -> None : "Save ` self . to _ df ( ) ` to a CSV file in ` self . path ` / ` dest ` ."
self . to_df ( ) . to_csv ( self . path / dest , index = False )
def show_system_monitor_output_switch_status_component_status_component_state ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_system_monitor = ET . Element ( "show_system_monitor" ) config = show_system_monitor output = ET . SubElement ( show_system_monitor , "output" ) switch_status = ET . SubElement ( output , "switch-status" ) component_status = ET . SubElement ( switch_status , "component-status" ) ...
def _process_long_opt ( self , rargs , values ) : """SCons - specific processing of long options . This is copied directly from the normal optparse . _ process _ long _ opt ( ) method , except that , if configured to do so , we catch the exception thrown when an unknown option is encountered and just stick ...
arg = rargs . pop ( 0 ) # Value explicitly attached to arg ? Pretend it ' s the next # argument . if "=" in arg : ( opt , next_arg ) = arg . split ( "=" , 1 ) rargs . insert ( 0 , next_arg ) had_explicit_value = True else : opt = arg had_explicit_value = False try : opt = self . _match_long_opt ...
def _Reg2Py ( data , size , data_type ) : """Converts a Windows Registry value to the corresponding Python data type ."""
if data_type == winreg . REG_DWORD : if size == 0 : return 0 # DWORD is an unsigned 32 - bit integer , see : # https : / / docs . microsoft . com / en - us / openspecs / windows _ protocols / ms - dtyp / 262627d8-3418-4627-9218-4ffe110850b2 return ctypes . cast ( data , ctypes . POINTER ( ctypes...
def qos_map_dscp_cos_mark_to ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" ) map = ET . SubElement ( qos , "map" ) dscp_cos = ET . SubElement ( map , "dscp-cos" ) dscp_cos_map_name_key = ET . SubElement ( dscp_cos , "dscp-cos-map-name" ) dscp_cos_map_name_key . text = kwargs ...
def average ( self , default = None ) : """Calculate the average value over the time series . : param default : Value to return as a default should the calculation not be possible . : return : Float representing the average value or ` None ` ."""
return numpy . asscalar ( numpy . average ( self . values ) ) if self . values else default
def temporal_from_rdf ( period_of_time ) : '''Failsafe parsing of a temporal coverage'''
try : if isinstance ( period_of_time , Literal ) : return temporal_from_literal ( str ( period_of_time ) ) elif isinstance ( period_of_time , RdfResource ) : return temporal_from_resource ( period_of_time ) except Exception : # There are a lot of cases where parsing could / should fail # but we ...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'gateway_id' ) and self . gateway_id is not None : _dict [ 'gateway_id' ] = self . gateway_id if hasattr ( self , 'name' ) and self . name is not None : _dict [ 'name' ] = self . name if hasattr ( self , 'status' ) and self . status is not None : _dict [ 'status' ] = self . s...
def parse_grid_xml ( self ) : """Parse the grid xyz and calculate the bounding box of the event . : raises : GridXmlParseError The grid xyz dataset looks like this : : < ? xml version = " 1.0 " encoding = " US - ASCII " standalone = " yes " ? > < shakemap _ grid xmlns : xsi = " http : / / www . w3 . org / 2...
LOGGER . debug ( 'ParseGridXml requested.' ) grid_path = self . grid_file_path ( ) try : document = minidom . parse ( grid_path ) shakemap_grid_element = document . getElementsByTagName ( 'shakemap_grid' ) shakemap_grid_element = shakemap_grid_element [ 0 ] self . event_id = shakemap_grid_element . attr...
def metrics ( * metrics ) : """Given a list of metrics , provides a builder that it turns computes metrics from a column . See the documentation of [ [ Summarizer ] ] for an example . The following metrics are accepted ( case sensitive ) : - mean : a vector that contains the coefficient - wise mean . - vari...
sc = SparkContext . _active_spark_context js = JavaWrapper . _new_java_obj ( "org.apache.spark.ml.stat.Summarizer.metrics" , _to_seq ( sc , metrics ) ) return SummaryBuilder ( js )
def serve_forever ( self ) : """Run the DAAP server . Start by advertising the server via Bonjour . Then serve requests until CTRL + C is received ."""
# Verify that the provider has a server . if self . provider . server is None : raise ValueError ( "Cannot start server because the provider has no server to " "publish." ) # Verify that the provider has a database to advertise . if not self . provider . server . databases : raise ValueError ( "Cannot start ser...
def geohash ( self , key , member , * members , ** kwargs ) : """Returns members of a geospatial index as standard geohash strings . : rtype : list [ str or bytes or None ]"""
return self . execute ( b'GEOHASH' , key , member , * members , ** kwargs )
def get_config_value ( self , section_name , option , default_option = "default" ) : """Read a value from the configuration , with a default . Args : section _ name ( str ) : name of the section in the configuration from which the option should be found . option ( str ) : name of the configuration option . ...
if self . config is None : self . config = configparser . ConfigParser ( ) self . config . read ( self . ini_file_name ) if option : try : return self . config . get ( section_name , option ) except configparser . NoOptionError : log . debug ( "Didn't find a configuration option for '%s'...
def sentiment ( self ) : """Returns average sentiment of document . Must have sentiment enabled in XML output . : getter : returns average sentiment of the document : type : float"""
if self . _sentiment is None : results = self . _xml . xpath ( '/root/document/sentences' ) self . _sentiment = float ( results [ 0 ] . get ( "averageSentiment" , 0 ) ) if len ( results ) > 0 else None return self . _sentiment
def doWaitWebRequest ( url , method = "GET" , data = None , headers = { } ) : """Same as doWebRequest , but with built in wait - looping"""
completed = False while not completed : completed = True try : response , content = doWebRequest ( url , method , data , headers ) except urllib2 . URLError : completed = False waitForURL ( url ) return response , content
def dataframe ( self ) : """Returns a pandas DataFrame containing all other class properties and values . The index for the DataFrame is the string abbreviation of the team , such as ' HOU ' ."""
fields_to_include = { 'abbreviation' : self . abbreviation , 'at_bats' : self . at_bats , 'average_batter_age' : self . average_batter_age , 'average_pitcher_age' : self . average_pitcher_age , 'away_losses' : self . away_losses , 'away_record' : self . away_record , 'away_wins' : self . away_wins , 'balks' : self . ba...
def update ( self , client = None , unique_writer_identity = False ) : """API call : update sink configuration via a PUT request See https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / projects . sinks / update : type client : : class : ` ~ google . cloud . logging . client . Clie...
client = self . _require_client ( client ) resource = client . sinks_api . sink_update ( self . project , self . name , self . filter_ , self . destination , unique_writer_identity = unique_writer_identity , ) self . _update_from_api_repr ( resource )
def get_form ( self , request , obj = None , ** kwargs ) : """Extend the form for the given plugin with the form SharableCascadeForm"""
Form = type ( str ( 'ExtSharableForm' ) , ( SharableCascadeForm , kwargs . pop ( 'form' , self . form ) ) , { } ) Form . base_fields [ 'shared_glossary' ] . limit_choices_to = dict ( plugin_type = self . __class__ . __name__ ) kwargs . update ( form = Form ) return super ( SharableGlossaryMixin , self ) . get_form ( re...
def send_events ( self , events ) : """Sends multiple events to Riemann in a single message : param events : A list or iterable of ` ` Event ` ` objects : returns : The response message from Riemann"""
message = riemann_client . riemann_pb2 . Msg ( ) for event in events : message . events . add ( ) . MergeFrom ( event ) return self . transport . send ( message )
def delete_entry ( self , fit = None , index = None ) : """deletes the single item from the logger of this object that corrisponds to either the passed in fit or index . Note this function mutaits the logger of this object if deleting more than one entry be sure to pass items to delete in from highest index to lowe...
if type ( index ) == int and not fit : fit , specimen = self . fit_list [ index ] if fit and type ( index ) == int : for i , ( f , s ) in enumerate ( self . fit_list ) : if fit == f : index , specimen = i , s break if index == self . current_fit_index : self . current_fit_ind...