signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def call_method_async ( self , method_name_or_object , params = None ) :
"""Calls the ` ` method _ name ` ` method from the given service asynchronously
and returns a : py : class : ` gemstone . client . structs . AsyncMethodCall ` instance .
: param method _ name _ or _ object : The name of te called method or... | thread_pool = self . _get_thread_pool ( )
if isinstance ( method_name_or_object , MethodCall ) :
req_obj = method_name_or_object
else :
req_obj = MethodCall ( method_name_or_object , params )
async_result_mp = thread_pool . apply_async ( self . handle_single_request , args = ( req_obj , ) )
return AsyncMethodCa... |
def match_notes ( ref_intervals , ref_pitches , ref_velocities , est_intervals , est_pitches , est_velocities , onset_tolerance = 0.05 , pitch_tolerance = 50.0 , offset_ratio = 0.2 , offset_min_tolerance = 0.05 , strict = False , velocity_tolerance = 0.1 ) :
"""Match notes , taking note velocity into consideration ... | # Compute note matching as usual using standard transcription function
matching = transcription . match_notes ( ref_intervals , ref_pitches , est_intervals , est_pitches , onset_tolerance , pitch_tolerance , offset_ratio , offset_min_tolerance , strict )
# Rescale reference velocities to the range [ 0 , 1]
min_velocity... |
def get_total_supply ( self ) -> int :
"""This interface is used to call the TotalSupply method in ope4
that return the total supply of the oep4 token .
: return : the total supply of the oep4 token .""" | func = InvokeFunction ( 'totalSupply' )
response = self . __sdk . get_network ( ) . send_neo_vm_transaction_pre_exec ( self . __hex_contract_address , None , func )
try :
total_supply = ContractDataParser . to_int ( response [ 'Result' ] )
except SDKException :
total_supply = 0
return total_supply |
def sendJobsStartNext ( self , statusDetails = None ) :
"""* * Description * *
Publishes an MQTT message to the StartNextJobExecution topic . This will attempt to get the next pending
job execution and change its status to IN _ PROGRESS .
* * Syntax * *
. . code : : python
# Start next job ( set status to... | topic = self . _thingJobManager . getJobTopic ( jobExecutionTopicType . JOB_START_NEXT_TOPIC , jobExecutionTopicReplyType . JOB_REQUEST_TYPE )
payload = self . _thingJobManager . serializeStartNextPendingJobExecutionPayload ( statusDetails )
return self . _AWSIoTMQTTClient . publish ( topic , payload , self . _QoS ) |
def slice ( string , start = None , end = None ) :
"""Returns a substring of the given string , counting graphemes instead of codepoints .
Negative indices is currently not supported .
> > > string = " tamil நி ( ni ) "
> > > string [ : 7]
' tamil ந '
> > > grapheme . slice ( string , end = 7)
' tamil ந... | if start is None :
start = 0
if end is not None and start >= end :
return ""
if start < 0 :
raise NotImplementedError ( "Negative indexing is currently not supported." )
sum_ = 0
start_index = None
for grapheme_index , grapheme_length in enumerate ( grapheme_lengths ( string ) ) :
if grapheme_index == s... |
def create_spot_requests ( self , price , instance_type = 'default' , root_device_type = 'ebs' , size = 'default' , vol_type = 'gp2' , delete_on_termination = False , timeout = None ) :
"""Request creation of one or more EC2 spot instances .
: param size :
: param vol _ type :
: param delete _ on _ terminatio... | name , size = self . _get_default_name_size ( instance_type , size )
if root_device_type == 'ebs' :
self . images [ instance_type ] [ 'block_device_map' ] = self . _configure_ebs_volume ( vol_type , name , size , delete_on_termination )
valid_until = None
if timeout is not None :
valid_until = ( datetime . date... |
def _unpack_tableswitch ( bc , offset ) :
"""function for unpacking the tableswitch op arguments""" | jump = ( offset % 4 )
if jump :
offset += ( 4 - jump )
( default , low , high ) , offset = _unpack ( _struct_iii , bc , offset )
joffs = list ( )
for _index in range ( ( high - low ) + 1 ) :
j , offset = _unpack ( _struct_i , bc , offset )
joffs . append ( j )
return ( default , low , high , joffs ) , offse... |
def defer ( coro , delay = 1 ) :
"""Returns a coroutine function wrapper that will defer the given coroutine
execution for a certain amount of seconds in a non - blocking way .
This function can be used as decorator .
Arguments :
coro ( coroutinefunction ) : coroutine function to defer .
delay ( int / flo... | assert_corofunction ( coro = coro )
@ asyncio . coroutine
def wrapper ( * args , ** kw ) : # Wait until we ' re done
yield from asyncio . sleep ( delay )
return ( yield from coro ( * args , ** kw ) )
return wrapper |
def dot ( self , other ) :
"""Compute the dot product between the Series and the columns of other .
This method computes the dot product between the Series and another
one , or the Series and each columns of a DataFrame , or the Series and
each columns of an array .
It can also be called using ` self @ othe... | from pandas . core . frame import DataFrame
if isinstance ( other , ( Series , DataFrame ) ) :
common = self . index . union ( other . index )
if ( len ( common ) > len ( self . index ) or len ( common ) > len ( other . index ) ) :
raise ValueError ( 'matrices are not aligned' )
left = self . reinde... |
def add ( self , item , count = 1 ) :
'''When we receive stream of data , we add them in the chunk
which has limit on the no . of items that it will store .
> > > s = StreamCounter ( 5,5)
> > > data _ stream = [ ' a ' , ' b ' , ' c ' , ' d ' ]
> > > for item in data _ stream :
. . . s . add ( item )
> >... | self . n_items_seen += count
self . n_chunk_items_seen += count
# get current chunk
chunk_id = self . n_chunks
chunk = self . chunked_counts . get ( chunk_id , { } )
self . chunked_counts [ chunk_id ] = chunk
# update count in the current chunk counter dict
if item in chunk :
chunk [ item ] += count
else :
self... |
def update_position ( self , loc ) :
"""Set the location of tick in data coords with scalar * loc * .""" | # This ensures that the new value of the location is set before
# any other updates take place .
self . _loc = loc
super ( SkewXTick , self ) . update_position ( loc ) |
def _change_color ( self , event ) :
"""Respond to motion of the hsv cursor .""" | h = self . bar . get ( )
self . square . set_hue ( h )
( r , g , b ) , ( h , s , v ) , sel_color = self . square . get ( )
self . red . set ( r )
self . green . set ( g )
self . blue . set ( b )
self . hue . set ( h )
self . saturation . set ( s )
self . value . set ( v )
self . hexa . delete ( 0 , "end" )
self . hexa ... |
def cookie_to_state ( cookie_str , name , encryption_key ) :
"""Loads a state from a cookie
: type cookie _ str : str
: type name : str
: type encryption _ key : str
: rtype : satosa . state . State
: param cookie _ str : string representation of cookie / s
: param name : Name identifier of the cookie
... | try :
cookie = SimpleCookie ( cookie_str )
state = State ( cookie [ name ] . value , encryption_key )
except KeyError as e :
msg_tmpl = 'No cookie named {name} in {data}'
msg = msg_tmpl . format ( name = name , data = cookie_str )
logger . exception ( msg )
raise SATOSAStateError ( msg ) from e
... |
def remote_restore_snapshot ( self , context , ports , snapshot_name ) :
"""Restores virtual machine from a snapshot
: param context : resource context of the vCenterShell
: type context : models . QualiDriverModels . ResourceCommandContext
: param ports : list [ string ] ports : the ports of the connection b... | return self . command_orchestrator . restore_snapshot ( context , snapshot_name ) |
def check_var_units ( self , ds ) :
'''Checks each applicable variable for the units attribute
: param netCDF4 . Dataset ds : An open netCDF dataset''' | results = [ ]
for variable in self . get_applicable_variables ( ds ) :
msgs = [ ]
# Check units and dims for variable
unit_check = hasattr ( ds . variables [ variable ] , 'units' )
no_dim_check = ( getattr ( ds . variables [ variable ] , 'dimensions' ) == tuple ( ) )
# Check if we have no dimensions... |
def get_inactive_status ( brain_or_object , default = "active" ) :
"""Get the ` cancellation _ state ` of an objct
: param brain _ or _ object : A single catalog brain or content object
: type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain
: returns : Value of the review _ status va... | if is_brain ( brain_or_object ) :
return getattr ( brain_or_object , "inactive_state" , default )
workflows = get_workflows_for ( brain_or_object )
if 'bika_inactive_workflow' not in workflows :
return default
return get_workflow_status_of ( brain_or_object , 'inactive_state' ) |
def close ( self , * args , ** kwargs ) :
"""Closes the websocket connection and waits for the ping thread to close""" | self . run_event . set ( )
self . ws . close ( )
if self . keepalive and self . keepalive . is_alive ( ) :
self . keepalive . join ( ) |
def list_engines ( zap_helper ) :
"""List engines that can be used to run scripts .""" | engines = zap_helper . zap . script . list_engines
console . info ( 'Available engines: {}' . format ( ', ' . join ( engines ) ) ) |
def _get_location ( cli_ctx , namespace ) :
"""Return an Azure location by using an explicit ` - - location ` argument , then by ` - - resource - group ` , and
finally by the subscription if neither argument was provided .""" | location = None
if getattr ( namespace , 'location' , None ) :
location = namespace . location
elif getattr ( namespace , 'resource_group_name' , None ) :
location = _get_location_from_resource_group ( cli_ctx , namespace . resource_group_name )
if not location :
location = get_one_of_subscription_locations... |
def cmd_legend ( self , args ) :
'''setup legend for graphs''' | if len ( args ) == 0 :
for leg in self . legend . keys ( ) :
print ( "%s -> %s" % ( leg , self . legend [ leg ] ) )
elif len ( args ) == 1 :
leg = args [ 0 ]
if leg in self . legend :
print ( "Removing legend %s" % leg )
self . legend . pop ( leg )
elif len ( args ) >= 2 :
leg = ... |
def progress ( self , * msg ) :
"""Prints a progress message""" | label = colors . purple ( "Progress" )
self . _msg ( label , * msg ) |
def _send_solr_command ( self , core_url , json_command ) :
"""Sends JSON string to Solr instance""" | # Check document language and dispatch to correct core
url = _get_url ( core_url , "update" )
try :
response = self . req_session . post ( url , data = json_command , headers = { 'Content-Type' : 'application/json' } )
response . raise_for_status ( )
except requests . RequestException as e :
logger . error ... |
def namespaced_view_name ( view_name , metric_prefix ) :
"""create string to be used as metric type""" | metric_prefix = metric_prefix or "custom.googleapis.com/opencensus"
return os . path . join ( metric_prefix , view_name ) . replace ( '\\' , '/' ) |
def build_template ( self , mapfile , names , renderer ) :
"""Build source from global and item templates""" | AVAILABLE_DUMPS = json . load ( open ( mapfile , "r" ) )
manager = self . get_deps_manager ( AVAILABLE_DUMPS )
fp = StringIO . StringIO ( )
for i , item in enumerate ( manager . get_dump_order ( names ) , start = 1 ) :
fp = renderer ( fp , i , item , manager [ item ] )
if self . dump_other_apps :
exclude_models... |
def ToJson ( self ) :
"""Convert object members to a dictionary that can be parsed as JSON .
Returns :
dict :""" | jsn = super ( MinerTransaction , self ) . ToJson ( )
jsn [ 'nonce' ] = self . Nonce
return jsn |
def list ( gandi , state , id , vhosts , type , limit ) :
"""List PaaS instances .""" | options = { 'items_per_page' : limit , }
if state :
options [ 'state' ] = state
output_keys = [ 'name' , 'state' ]
if id :
output_keys . append ( 'id' )
if vhosts :
output_keys . append ( 'vhost' )
if type :
output_keys . append ( 'type' )
paas_hosts = { }
result = gandi . paas . list ( options )
for nu... |
def _sc_encode ( gain , peak ) :
"""Encode ReplayGain gain / peak values as a Sound Check string .""" | # SoundCheck stores the peak value as the actual value of the
# sample , rather than the percentage of full scale that RG uses , so
# we do a simple conversion assuming 16 bit samples .
peak *= 32768.0
# SoundCheck stores absolute RMS values in some unknown units rather
# than the dB values RG uses . We can calculate t... |
def serve ( ip , port , application , ssl = None , processes = 1 , ** kwargs ) :
"""Serve a wsgi app ( any wsgi app ) through with either werkzeug ' s runserver
or the one that comes with python . Setting ` processes ` to anything other than 1
will prevent the debigger from working .""" | try : # use werkzeug if its there
from werkzeug . serving import run_simple
print ( "Using Werkzeug run_simple" )
run_simple ( ip , port , application , ssl_context = ssl , processes = processes , ** kwargs )
return
except ImportError :
pass
# otherwise just use python ' s built in wsgi webserver
fr... |
def preprocess ( s ) :
"""> > > preprocess ( ' # hi there http : / / www . foo . com @ you isn " t RT & lt ; & gt ; ' )
' hashtaghi hashtaghi there isn " t '""" | # s = re . sub ( ' @ \ S + ' , ' thisisamention ' , s ) # map all mentions to thisisamention
s = re . sub ( r'@\S+' , ' ' , s )
# map all mentions to thisisamention
# s = re . sub ( ' http \ S + ' , ' http ' , s ) # keep only http from urls
s = re . sub ( r'http\S+' , ' ' , s )
# keep only http from urls
s = re . sub (... |
def get_partition_function ( self ) :
"""Returns the partition function for a given undirected graph .
A partition function is defined as
. . math : : \ sum _ { X } ( \ prod _ { i = 1 } ^ { m } \ phi _ i )
where m is the number of factors present in the graph
and X are all the random variables present .
E... | self . check_model ( )
factor = self . factors [ 0 ]
factor = factor_product ( factor , * [ self . factors [ i ] for i in range ( 1 , len ( self . factors ) ) ] )
if set ( factor . scope ( ) ) != set ( self . nodes ( ) ) :
raise ValueError ( 'DiscreteFactor for all the random variables not defined.' )
return np . s... |
def _dataframe_fields ( self ) :
"""Creates a dictionary of all fields to include with DataFrame .
With the result of the calls to class properties changing based on the
class index value , the dictionary should be regenerated every time the
index is changed when the dataframe property is requested .
Return... | fields_to_include = { 'assist_percentage' : self . assist_percentage , 'assists' : self . assists , 'block_percentage' : self . block_percentage , 'blocks' : self . blocks , 'box_plus_minus' : self . box_plus_minus , 'conference' : self . conference , 'defensive_box_plus_minus' : self . defensive_box_plus_minus , 'defe... |
def parse ( file_path ) :
"""Return a decoded API to the data from a file path .
: param file _ path : the input file path . Data is not entropy compressed ( e . g . gzip )
: return an API to decoded data""" | newDecoder = MMTFDecoder ( )
with open ( file_path , "rb" ) as fh :
newDecoder . decode_data ( _unpack ( fh ) )
return newDecoder |
def parse_size ( image , size ) :
"""Parse a size string ( i . e . " 200 " , " 200x100 " , " x200 " , etc . ) into a
( width , height ) tuple .""" | bits = size . split ( "x" )
if image . size [ 0 ] == 0 or image . size [ 1 ] == 0 :
ratio = 1.0
else :
ratio = float ( image . size [ 0 ] ) / float ( image . size [ 1 ] )
if len ( bits ) == 1 or not bits [ 1 ] :
width = int ( bits [ 0 ] )
height = int ( 1 / ratio * width )
elif not bits [ 0 ] :
heig... |
def _write_entries ( self , stream , entries , converter , properties = None ) :
"""Write iterable of entries as YAML object to stream .
Args :
stream : File - like object .
entries : Iterable of entries .
converter : Conversion function from entry to YAML object .
properties : Set of compartment properti... | def iter_entries ( ) :
for c in entries :
entry = converter ( c )
if entry is None :
continue
if properties is not None :
entry = OrderedDict ( ( key , value ) for key , value in iteritems ( entry ) if key == 'id' or key in properties )
yield entry
self . _dum... |
def convert_ints_to_bytes ( in_ints , num ) :
"""Convert an integer array into a byte arrays . The number of bytes forming an integer
is defined by num
: param in _ ints : the input integers
: param num : the number of bytes per int
: return the integer array""" | out_bytes = b""
for val in in_ints :
out_bytes += struct . pack ( mmtf . utils . constants . NUM_DICT [ num ] , val )
return out_bytes |
def process_line ( self , line ) :
"Process a single complete line ." | cleaned = [ ]
columns = line . split ( self . indel )
# Populate indices if not defined
if not self . indices :
self . indices = range ( len ( columns ) )
for i in self . indices : # Support turning an in col into multiple out cols
out = self . process_column ( i , columns [ i ] )
if isinstance ( out , ( li... |
def iterate ( self , index , step , n_cols = 70 ) :
"""Return an iterator that starts and the current index and increments
by the given step .""" | while True :
if step < 0 and index < 0 : # Hack to prevent displaying a submission ' s post if iterating
# comments in the negative direction
break
try :
yield self . get ( index , n_cols = n_cols )
except IndexError :
break
index += step |
def validate ( self , value ) :
"""Return a boolean if the value is valid""" | try :
self . _choice = IPAddress ( value )
return True
except ( ValueError , AddrFormatError ) :
self . error_message = '%s is not a valid IP address.' % value
return False |
def indicators ( self , indicator_data ) :
"""Generator for indicator values .
Some indicator such as Files ( hashes ) and Custom Indicators can have multiple indicator
values ( e . g . md5 , sha1 , sha256 ) . This method provides a generator to iterate over all
indicator values .
Both the * * summary * * f... | # indicator _ list = [ ]
for indicator_field in self . value_fields :
if indicator_field == 'summary' :
indicators = self . tcex . expand_indicators ( indicator_data . get ( 'summary' ) )
if indicator_data . get ( 'type' ) == 'File' :
hash_patterns = { 'md5' : re . compile ( r'^([a-fA-F\... |
def perform_action ( self , action , machines , params , progress_title , success_title ) :
"""Perform the action on the set of machines .""" | if len ( machines ) == 0 :
return 0
with utils . Spinner ( ) as context :
return self . _async_perform_action ( context , action , list ( machines ) , params , progress_title , success_title ) |
def get_password ( hsm , args ) :
"""Get password of correct length for this YubiHSM version .""" | expected_len = 32
name = 'HSM password'
if hsm . version . have_key_store_decrypt ( ) :
expected_len = 64
name = 'master key'
if args . stdin :
password = sys . stdin . readline ( )
while password and password [ - 1 ] == '\n' :
password = password [ : - 1 ]
else :
if args . debug :
p... |
def expire ( self , current_time = None ) :
"""Expire any old entries
` current _ time `
Optional time to be used to clean up queue ( can be used in unit tests )""" | if not self . _queue :
return
if current_time is None :
current_time = time ( )
while self . _queue : # Get top most item
top = self . _queue [ 0 ]
# Early exit if item was not promoted and its expiration time
# is greater than now .
if top . promoted is None and top . expiry_date > current_time... |
def bucket ( cls , bucket_name , connection = None ) :
"""Gives the bucket from couchbase server .
: param bucket _ name : Bucket name to fetch .
: type bucket _ name : str
: returns : couchbase driver ' s Bucket object .
: rtype : : class : ` couchbase . client . Bucket `
: raises : : exc : ` RuntimeErro... | connection = cls . connection if connection == None else connection
if bucket_name not in cls . _buckets :
connection = "{connection}/{bucket_name}" . format ( connection = connection , bucket_name = bucket_name )
if cls . password :
cls . _buckets [ connection ] = Bucket ( connection , password = cls .... |
def process_exception ( self , request , e ) :
"""Still process session data when specially Exception""" | if isinstance ( e , RedirectException ) :
response = e . get_response ( )
self . process_response ( request , response ) |
def disconnect ( self , format , * args ) :
"""Disconnect a socket from a formatted endpoint
Returns 0 if OK , - 1 if the endpoint was invalid or the function
isn ' t supported .""" | return lib . zsock_disconnect ( self . _as_parameter_ , format , * args ) |
def _make_wildcard_attr_map ( ) :
'''Create a dictionary that maps an attribute name
in OpenflowMatch with a non - prefix - related wildcard
bit from the above OpenflowWildcard enumeration .''' | _xmap = { }
for wc in OpenflowWildcard :
if not wc . name . endswith ( 'All' ) and not wc . name . endswith ( 'Mask' ) :
translated = ''
for ch in wc . name :
if ch . isupper ( ) :
translated += '_'
translated += ch . lower ( )
else :
... |
def runserver ( app = None , reloader = None , debug = None , host = None , port = None ) :
"""Run the Flask development server i . e . app . run ( )""" | debug = debug or app . config . get ( 'DEBUG' , False )
reloader = reloader or app . config . get ( 'RELOADER' , False )
host = host or app . config . get ( 'HOST' , '127.0.0.1' )
port = port or app . config . get ( 'PORT' , 5000 )
app . run ( use_reloader = reloader , debug = debug , host = host , port = port ) |
def bind_events ( self , events ) :
'''Register all known events found in ` ` events ` ` key - valued parameters .''' | evs = self . _events
if evs and events :
for event in evs . values ( ) :
if event . name in events :
event . bind ( events [ event . name ] ) |
def add_blacklisted_directories ( self , directories , rm_black_dirs_from_stored_dirs = True ) :
"""Adds ` directories ` to be blacklisted . Blacklisted directories will not
be returned or searched recursively when calling the
` collect _ directories ` method .
` directories ` may be a single instance or an i... | add_black_dirs = self . directory_manager . add_blacklisted_directories
add_black_dirs ( directories , rm_black_dirs_from_stored_dirs ) |
def _check_lib ( self , remake , compiler , debug , profile ) :
"""Makes sure that the linked library with the original code exists . If it doesn ' t
the library is compiled from scratch .""" | from os import path
if self . link is None or not path . isfile ( self . link ) :
self . makelib ( remake , True , compiler , debug , profile ) |
def function ( self , x , y , sigma0 , Rs , center_x = 0 , center_y = 0 ) :
"""lensing potential
: param x :
: param y :
: param sigma0 : sigma0 / sigma _ crit
: param a :
: param s :
: param center _ x :
: param center _ y :
: return :""" | x_ = x - center_x
y_ = y - center_y
r = np . sqrt ( x_ ** 2 + y_ ** 2 )
if isinstance ( r , int ) or isinstance ( r , float ) :
r = max ( self . _s , r )
else :
r [ r < self . _s ] = self . _s
X = r / Rs
f_ = sigma0 * Rs ** 2 * ( np . log ( X ** 2 / 4. ) + 2 * self . _F ( X ) )
return f_ |
def find_manifests ( self ) :
'''locate manifests and return filepaths thereof''' | manifest_dir = mp_util . dot_mavproxy ( )
ret = [ ]
for file in os . listdir ( manifest_dir ) :
try :
file . index ( "manifest" )
ret . append ( os . path . join ( manifest_dir , file ) )
except ValueError :
pass
return ret |
def extractColumns ( TableName , SourceParameterName , ParameterFormats , ParameterNames = None , FixCol = False ) :
"""INPUT PARAMETERS :
TableName : name of source table ( required )
SourceParameterName : name of source column to process ( required )
ParameterFormats : c formats of unpacked parameters ( req... | # ParameterNames = just the names without expressions
# ParFormats contains python formats for par extraction
# Example : ParameterNames = ( ' v1 ' , ' v2 ' , ' v3 ' )
# ParameterFormats = ( ' % 1s ' , ' % 1s ' , ' % 1s ' )
# By default the format of parameters is column - fixed
if type ( LOCAL_TABLE_CACHE [ TableName ... |
def get_listener ( name ) :
'''Return the listener class .''' | try :
log . debug ( 'Using %s as listener' , name )
return LISTENER_LOOKUP [ name ]
except KeyError :
msg = 'Listener {} is not available. Are the dependencies installed?' . format ( name )
log . error ( msg , exc_info = True )
raise InvalidListenerException ( msg ) |
def DeleteGroupTags ( r , group , tags , dry_run = False ) :
"""Deletes tags from a node group .
@ type group : str
@ param group : group to delete tags from
@ type tags : list of string
@ param tags : tags to delete
@ type dry _ run : bool
@ param dry _ run : whether to perform a dry run
@ rtype : st... | query = { "dry-run" : dry_run , "tag" : tags , }
return r . request ( "delete" , "/2/groups/%s/tags" % group , query = query ) |
def expand_path ( experiment_config , key ) :
'''Change ' ~ ' to user home directory''' | if experiment_config . get ( key ) :
experiment_config [ key ] = os . path . expanduser ( experiment_config [ key ] ) |
def uniq ( args ) :
"""% prog uniq vcffile
Retain only the first entry in vcf file .""" | from six . moves . urllib . parse import parse_qs
p = OptionParser ( uniq . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
vcffile , = args
fp = must_open ( vcffile )
data = [ ]
for row in fp :
if row [ 0 ] == '#' :
print ( row . strip ( ) )
... |
def _get_line_type ( line ) :
'''Decide the line type in function of its contents''' | stripped = line . strip ( )
if not stripped :
return 'empty'
remainder = re . sub ( r"\s+" , " " , re . sub ( CHORD_RE , "" , stripped ) )
if len ( remainder ) * 2 < len ( re . sub ( r"\s+" , " " , stripped ) ) :
return 'chord'
return 'lyric' |
def generate_random_perovskite ( lat = None ) :
'''This generates a random valid perovskite structure in ASE format .
Useful for testing .
Binary and organic perovskites are not considered .''' | if not lat :
lat = round ( random . uniform ( 3.5 , Perovskite_tilting . OCTAHEDRON_BOND_LENGTH_LIMIT * 2 ) , 3 )
A_site = random . choice ( Perovskite_Structure . A )
B_site = random . choice ( Perovskite_Structure . B )
Ci_site = random . choice ( Perovskite_Structure . C )
Cii_site = random . choice ( Perovskite... |
def setQuery ( self , query ) :
"""Set the SPARQL query text and set the VIVO custom
authentication parameters .
Set here because this is called immediately before
any query is sent to the triple store .""" | self . queryType = self . _parseQueryType ( query )
self . queryString = self . injectPrefixes ( query )
self . addParameter ( 'email' , self . email )
self . addParameter ( 'password' , self . password ) |
def mcscanq ( args ) :
"""% prog mcscanq query . ids blocksfile
Query multiple synteny blocks to get the closest alignment feature . Mostly
used for ' highlighting ' the lines in the synteny plot , drawn by
graphics . karyotype and graphics . synteny .""" | p = OptionParser ( mcscanq . __doc__ )
p . add_option ( "--color" , help = "Add color highlight, used in plotting" )
p . add_option ( "--invert" , default = False , action = "store_true" , help = "Invert query and subject [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) < 2 :
sys . exit ... |
def login_as_bot ( ) :
"""Login as the bot account " octogrid " , if user isn ' t authenticated on Plotly""" | plotly_credentials_file = join ( join ( expanduser ( '~' ) , PLOTLY_DIRECTORY ) , PLOTLY_CREDENTIALS_FILENAME )
if isfile ( plotly_credentials_file ) :
with open ( plotly_credentials_file , 'r' ) as f :
credentials = loads ( f . read ( ) )
if ( credentials [ 'username' ] == '' or credentials [ 'api_key'... |
def get_bandstructure ( self ) :
"""returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter""" | return LobsterBandStructureSymmLine ( kpoints = self . kpoints_array , eigenvals = self . eigenvals , lattice = self . lattice , efermi = self . efermi , labels_dict = self . label_dict , structure = self . structure , projections = self . p_eigenvals ) |
def build_object ( self , obj ) :
"""Override django - bakery to skip profiles that raise 404""" | try :
build_path = self . get_build_path ( obj )
self . request = self . create_request ( build_path )
self . request . user = AnonymousUser ( )
self . set_kwargs ( obj )
self . build_file ( build_path , self . get_content ( ) )
except Http404 : # cleanup directory
self . unbuild_object ( obj ) |
def get_boolean ( self , key , optional = False ) :
"""Tries to fetch a variable from the config and expects it to be a truthy value . This could be a string ( " 1 " , " Y " )
or an actual boolean . This is because we use the strtobool function in the case we find a string . The function
strtobool expects value... | return self . _get_typed_value ( key , bool , lambda x : bool ( util . strtobool ( x ) ) , optional ) |
def add ( self , name , monitor = True ) :
"""Add a folder , library ( . py ) or resource file ( . robot , . tsv , . txt ) to the database""" | if os . path . isdir ( name ) :
if ( not os . path . basename ( name ) . startswith ( "." ) ) :
self . add_folder ( name )
elif os . path . isfile ( name ) :
if ( ( self . _looks_like_resource_file ( name ) ) or ( self . _looks_like_libdoc_file ( name ) ) or ( self . _looks_like_library_file ( name ) ) ... |
def get_all_files_in_range ( dirname , starttime , endtime , pad = 64 ) :
"""Returns all files in dirname and all its subdirectories whose
names indicate that they contain segments in the range starttime
to endtime""" | ret = [ ]
# Maybe the user just wants one file . . .
if os . path . isfile ( dirname ) :
if re . match ( '.*-[0-9]*-[0-9]*\.xml$' , dirname ) :
return [ dirname ]
else :
return ret
first_four_start = starttime / 100000
first_four_end = endtime / 100000
for filename in os . listdir ( dirname ) :
... |
def smoothed ( self , iterations = 1 ) :
"""Return a smoothed copy of this histogram
Parameters
iterations : int , optional ( default = 1)
The number of smoothing iterations
Returns
hist : asrootpy ' d histogram
The smoothed histogram""" | copy = self . Clone ( shallow = True )
copy . Smooth ( iterations )
return copy |
def update ( self ) :
"""Updates the bundle""" | with self . _lock : # Was it active ?
restart = self . _state == Bundle . ACTIVE
# Send the update event
self . _fire_bundle_event ( BundleEvent . UPDATE_BEGIN )
try : # Stop the bundle
self . stop ( )
except : # Something wrong occurred , notify listeners
self . _fire_bundle_event (... |
def connect ( ip , _initialize = True , wait_ready = None , timeout = 30 , still_waiting_callback = default_still_waiting_callback , still_waiting_interval = 1 , status_printer = None , vehicle_class = None , rate = 4 , baud = 115200 , heartbeat_timeout = 30 , source_system = 255 , source_component = 0 , use_native = F... | from dronekit . mavlink import MAVConnection
if not vehicle_class :
vehicle_class = Vehicle
handler = MAVConnection ( ip , baud = baud , source_system = source_system , source_component = source_component , use_native = use_native )
vehicle = vehicle_class ( handler )
if status_printer :
vehicle . _autopilot_lo... |
def myFunc ( parameter ) :
"""This function will be executed on the remote host even if it was not
available at launch .""" | print ( 'Hello World from {0}!' . format ( scoop . worker ) )
# It is possible to get a constant anywhere
print ( shared . getConst ( 'myVar' ) [ 2 ] )
# Parameters are handled as usual
return parameter + 1 |
def compose_layer ( layer , force = False , ** kwargs ) :
"""Compose a single layer with pixels .""" | from PIL import Image , ImageChops
assert layer . bbox != ( 0 , 0 , 0 , 0 ) , 'Layer bbox is (0, 0, 0, 0)'
image = layer . topil ( ** kwargs )
if image is None or force :
texture = create_fill ( layer )
if texture is not None :
image = texture
if image is None :
return image
# TODO : Group should ha... |
def formatted_completion_sig ( completion ) :
"""Regenerate signature for methods . Return just the name otherwise""" | f_result = completion [ "name" ]
if is_basic_type ( completion ) : # It ' s a raw type
return f_result
elif len ( completion [ "typeInfo" ] [ "paramSections" ] ) == 0 :
return f_result
# It ' s a function type
sections = completion [ "typeInfo" ] [ "paramSections" ]
f_sections = [ formatted_param_section ( ps )... |
def make_grasp_phenotype_file ( fn , pheno , out ) :
"""Subset the GRASP database on a specific phenotype .
Parameters
fn : str
Path to GRASP database file .
pheno : str
Phenotype to extract from database .
out : sttr
Path to output file for subset of GRASP database .""" | import subprocess
c = 'awk -F "\\t" \'NR == 1 || $12 == "{}" \' {} > {}' . format ( pheno . replace ( "'" , '\\x27' ) , fn , out )
subprocess . check_call ( c , shell = True ) |
def playlists ( self ) :
"""获取用户创建的歌单
如果不是用户本人 , 则不能获取用户默认精选集""" | if self . _playlists is None :
playlists_data = self . _api . user_playlists ( self . identifier )
playlists = [ ]
for playlist_data in playlists_data :
playlist = _deserialize ( playlist_data , PlaylistSchema )
playlists . append ( playlist )
self . _playlists = playlists
return self . ... |
def _extract_header_value ( line ) :
"""Extracts a key / value pair from a header line in an ODF file""" | # Skip blank lines , returning None
if not line :
return None
# Attempt to split by equals sign
halves = line . split ( '=' )
if len ( halves ) > 1 :
key = halves [ 0 ] . strip ( )
value = halves [ 1 ] . strip ( )
return { key : value }
# Otherwise , attempt to split by colon
else :
halves = line . ... |
def _coerceSingleRepetition ( self , dataSet ) :
"""Make a new liveform with our parameters , and get it to coerce our data
for us .""" | # make a liveform because there is some logic in _ coerced
form = LiveForm ( lambda ** k : None , self . parameters , self . name )
return form . fromInputs ( dataSet ) |
def bottleneck_block ( inputs , filters , is_training , strides , projection_shortcut = None , row_blocks_dim = None , col_blocks_dim = None ) :
"""Bottleneck block variant for residual networks with BN after convolutions .
Args :
inputs : a ` mtf . Tensor ` of shape
` [ batch _ dim , row _ blocks , col _ blo... | shortcut = inputs
filter_h_dim = mtf . Dimension ( "filter_height" , 3 )
filter_w_dim = mtf . Dimension ( "filter_width" , 3 )
one_h_dim = mtf . Dimension ( "filter_height" , 1 )
one_w_dim = mtf . Dimension ( "filter_width" , 1 )
if projection_shortcut is not None :
filters_dim = mtf . Dimension ( "filtersp" , filt... |
def datetime_to_year_quarter ( dt ) :
"""Args :
dt : a datetime
Returns :
tuple of the datetime ' s year and quarter""" | year = dt . year
quarter = int ( math . ceil ( float ( dt . month ) / 3 ) )
return ( year , quarter ) |
def get_all ( self , key : str ) -> List [ str ] :
"""Return the ( possibly empty ) list of all values for a header .""" | return self . _dict . get ( key . lower ( ) , [ ] ) |
def attach ( cls , name , vhost , remote_name ) :
"""Attach an instance ' s vhost to a remote from the local repository .""" | paas_access = cls . get ( 'paas_access' )
if not paas_access :
paas_info = cls . info ( name )
paas_access = '%s@%s' % ( paas_info [ 'user' ] , paas_info [ 'git_server' ] )
remote_url = 'ssh+git://%s/%s.git' % ( paas_access , vhost )
ret = cls . execute ( 'git remote add %s %s' % ( remote_name , remote_url , ) ... |
def new_consolidate ( self , result , batch_result ) :
'''Used so that it can work with the multiprocess plugin .
Monkeypatched because nose seems a bit unsupported at this time ( ideally
the plugin would have this support by default ) .''' | ret = original ( self , result , batch_result )
parent_frame = sys . _getframe ( ) . f_back
# addr is something as D : \ pytesting1 \ src \ mod1 \ hello . py : TestCase . testMet4
# so , convert it to what report _ cond expects
addr = parent_frame . f_locals [ 'addr' ]
i = addr . rindex ( ':' )
addr = [ addr [ : i ] , ... |
def guess_fill_char ( left_comp , right_comp ) :
"""For the case where there is no annotated synteny we will try to guess it""" | # No left component , obiously new
return "*"
# First check that the blocks have the same src ( not just species ) and
# orientation
if ( left_comp . src == right_comp . src and left_comp . strand != right_comp . strand ) : # Are they completely contiguous ? Easy to call that a gap
if left_comp . end == right_comp ... |
def send_sticker ( self , sticker , ** options ) :
"""Send a sticker to the chat .
: param sticker : Sticker to send ( file or string )
: param options : Additional sendSticker options ( see
https : / / core . telegram . org / bots / api # sendsticker )""" | return self . bot . api_call ( "sendSticker" , chat_id = str ( self . id ) , sticker = sticker , ** options ) |
def _get_container ( self , path ) :
"""Return single container .""" | cont = self . native_conn . get_container ( path )
return self . cont_cls ( self , cont . name , cont . object_count , cont . size_used ) |
def get_pubkey_hex ( privatekey_hex ) :
"""Get the uncompressed hex form of a private key""" | if not isinstance ( privatekey_hex , ( str , unicode ) ) :
raise ValueError ( "private key is not a hex string but {}" . format ( str ( type ( privatekey_hex ) ) ) )
# remove ' compressed ' hint
if len ( privatekey_hex ) > 64 :
if privatekey_hex [ - 2 : ] != '01' :
raise ValueError ( "private key does n... |
def warning ( cls , template , default_params = { } , cause = None , stack_depth = 0 , log_context = None , ** more_params ) :
""": param template : * string * human readable string with placeholders for parameters
: param default _ params : * dict * parameters to fill in template
: param cause : * Exception * ... | timestamp = datetime . utcnow ( )
if not is_text ( template ) :
Log . error ( "Log.warning was expecting a unicode template" )
if isinstance ( default_params , BaseException ) :
cause = default_params
default_params = { }
if "values" in more_params . keys ( ) :
Log . error ( "Can not handle a logging pa... |
def close ( self ) :
'''close the Mission Editor window''' | self . time_to_quit = True
self . close_window . release ( )
if self . child . is_alive ( ) :
self . child . join ( 1 )
self . child . terminate ( )
self . mavlink_message_queue_handler . join ( )
self . event_queue_lock . acquire ( )
self . event_queue . put ( MissionEditorEvent ( me_event . MEE_TIME_TO_QUIT ) ) ;... |
def pull_full_properties ( self ) :
"""Retrieve the full set of resource properties and cache them in this
object .
Authorization requirements :
* Object - access permission to this resource .
Raises :
: exc : ` ~ zhmcclient . HTTPError `
: exc : ` ~ zhmcclient . ParseError `
: exc : ` ~ zhmcclient . ... | full_properties = self . manager . session . get ( self . _uri )
self . _properties = dict ( full_properties )
self . _properties_timestamp = int ( time . time ( ) )
self . _full_properties = True |
def set_publicId ( self , publicId ) :
'''Sets the publicId to the public object
@ param publicId : a publicId ( title of article )
@ type publicId : string''' | publicObj = self . get_public ( )
if publicObj is not None :
publicObj . set_publicid ( publicId )
else :
publicObj = Cpublic ( )
publicObj . set_publicid ( publicId )
self . set_public ( publicObj ) |
def authorize_url ( self , duration , scopes , state , implicit = False ) :
"""Return the URL used out - of - band to grant access to your application .
: param duration : Either ` ` permanent ` ` or ` ` temporary ` ` . ` ` temporary ` `
authorizations generate access tokens that last only 1
hour . ` ` perman... | if self . redirect_uri is None :
raise InvalidInvocation ( "redirect URI not provided" )
if implicit and not isinstance ( self , UntrustedAuthenticator ) :
raise InvalidInvocation ( "Only UntrustedAuthentictor instances can " "use the implicit grant flow." )
if implicit and duration != "temporary" :
raise I... |
def process_doc ( self , doc ) :
"""Attempt to parse an xml string conforming to either an SOS or SensorML
dataset and return the results""" | xml_doc = ET . fromstring ( doc )
if xml_doc . tag == "{http://www.opengis.net/sos/1.0}Capabilities" :
ds = SensorObservationService ( None , xml = doc )
# SensorObservationService does not store the etree doc root ,
# so maybe use monkey patching here for now ?
ds . _root = xml_doc
elif xml_doc . tag =... |
def write ( self ) :
"""write the current settings to the config file""" | with open ( storage . config_file , 'w' ) as cfg :
yaml . dump ( self . as_dict ( ) , cfg , default_flow_style = False )
storage . refresh ( ) |
def _construct_location_to_filter_list ( match_query ) :
"""Return a dict mapping location - > list of filters applied at that location .
Args :
match _ query : MatchQuery object from which to extract location - > filters dict
Returns :
dict mapping each location in match _ query to a list of
Filter objec... | # For each location , all filters for that location should be applied at the first instance .
# This function collects a list of all filters corresponding to each location
# present in the given MatchQuery .
location_to_filters = { }
for match_traversal in match_query . match_traversals :
for match_step in match_tr... |
def solve_linear_diop ( total : int , * coeffs : int ) -> Iterator [ Tuple [ int , ... ] ] :
r"""Yield non - negative integer solutions of a linear Diophantine equation of the format
: math : ` c _ 1 x _ 1 + \ dots + c _ n x _ n = total ` .
If there are at most two coefficients , : func : ` base _ solution _ li... | if len ( coeffs ) == 0 :
if total == 0 :
yield tuple ( )
return
if len ( coeffs ) == 1 :
if total % coeffs [ 0 ] == 0 :
yield ( total // coeffs [ 0 ] , )
return
if len ( coeffs ) == 2 :
yield from base_solution_linear ( coeffs [ 0 ] , coeffs [ 1 ] , total )
return
# calculate gcd... |
def _safe_call ( obj , methname , * args , ** kwargs ) :
"""Safely calls the method with the given methname on the given
object . Remaining positional and keyword arguments are passed to
the method . The return value is None , if the method is not
available , or the return value of the method .""" | meth = getattr ( obj , methname , None )
if meth is None or not callable ( meth ) :
return
return meth ( * args , ** kwargs ) |
def save ( self ) :
"""Override the save method to save the first and last name to the user
field .""" | # First save the parent form and get the user .
new_user = super ( SignupFormExtra , self ) . save ( )
new_user . first_name = self . cleaned_data [ 'first_name' ]
new_user . last_name = self . cleaned_data [ 'last_name' ]
new_user . save ( )
# Userena expects to get the new user from this form , so return the new
# us... |
def _is_label_or_level_reference ( self , key , axis = 0 ) :
"""Test whether a key is a label or level reference for a given axis .
To be considered either a label or a level reference , ` key ` must be a
string that :
- ( axis = 0 ) : Matches a column label or an index level
- ( axis = 1 ) : Matches an ind... | if self . ndim > 2 :
raise NotImplementedError ( "_is_label_or_level_reference is not implemented for {type}" . format ( type = type ( self ) ) )
return ( self . _is_level_reference ( key , axis = axis ) or self . _is_label_reference ( key , axis = axis ) ) |
def _encodeAddressField ( address , smscField = False ) :
"""Encodes the address into an address field
: param address : The address to encode ( phone number or alphanumeric )
: type byteIter : str
: return : Encoded SMS PDU address field
: rtype : bytearray""" | # First , see if this is a number or an alphanumeric string
toa = 0x80 | 0x00 | 0x01
# Type - of - address start | Unknown type - of - number | ISDN / tel numbering plan
alphaNumeric = False
if address . isalnum ( ) : # Might just be a local number
if address . isdigit ( ) : # Local number
toa |= 0x20
e... |
def render_profile_data ( self , as_parsed ) :
"""Render the chosen profile entry , as it was parsed .""" | try :
return deep_map ( self . _render_profile_data , as_parsed )
except RecursionException :
raise DbtProfileError ( 'Cycle detected: Profile input has a reference to itself' , project = as_parsed ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.