signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def __remote_path_rewrite ( self , dataset_path , dataset_path_type , name = None ) :
"""Return remote path of this file ( if staging is required ) else None .""" | path = str ( dataset_path )
# Use false _ path if needed .
action = self . action_mapper . action ( path , dataset_path_type )
if action . staging_needed :
if name is None :
name = os . path . basename ( path )
remote_directory = self . __remote_directory ( dataset_path_type )
remote_path_rewrite = ... |
def getitem_by_path ( d , path ) :
"""Access item in d using path .
a = { 0 : { 1 : ' item ' } }
getitem _ by _ path ( a , [ 0 , 1 ] ) = = ' item '""" | return reduce ( lambda d , k : d [ k ] , path , d ) |
def get_similar_transcripts ( self , tx_ac ) :
"""Return a list of transcripts that are similar to the given
transcript , with relevant similarity criteria .
> > sim _ tx = hdp . get _ similar _ transcripts ( ' NM _ 001285829.1 ' )
> > dict ( sim _ tx [ 0 ] )
{ ' cds _ eq ' : False ,
' cds _ es _ fp _ eq ... | rows = self . _fetchall ( self . _queries [ 'tx_similar' ] , [ tx_ac ] )
return rows |
def content_edge_check ( self , url ) :
"""Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server .""" | prefixes = [ "http://" , "https://" ]
for prefix in prefixes :
if url . startswith ( prefix ) :
url = url [ len ( prefix ) : ]
break
content = self . _fetch ( "/content/edge_check/%s" % url )
return content |
def create_mon_path ( path , uid = - 1 , gid = - 1 ) :
"""create the mon path if it does not exist""" | if not os . path . exists ( path ) :
os . makedirs ( path )
os . chown ( path , uid , gid ) ; |
def extract_lzh ( archive , compression , cmd , verbosity , interactive , outdir ) :
"""Extract a LZH archive .""" | opts = 'x'
if verbosity > 1 :
opts += 'v'
opts += "w=%s" % outdir
return [ cmd , opts , archive ] |
def RunWMIQuery ( query , baseobj = r"winmgmts:\root\cimv2" ) :
"""Run a WMI query and return a result .
Args :
query : the WMI query to run .
baseobj : the base object for the WMI query .
Yields :
rdf _ protodict . Dicts containing key value pairs from the resulting COM
objects .""" | pythoncom . CoInitialize ( )
# Needs to be called if using com from a thread .
wmi_obj = win32com . client . GetObject ( baseobj )
# This allows our WMI to do some extra things , in particular
# it gives it access to find the executable path for all processes .
wmi_obj . Security_ . Privileges . AddAsString ( "SeDebugP... |
def _unpickle_sparse_frame_compat ( self , state ) :
"""Original pickle format""" | series , cols , idx , fv , kind = state
if not isinstance ( cols , Index ) : # pragma : no cover
from pandas . io . pickle import _unpickle_array
columns = _unpickle_array ( cols )
else :
columns = cols
if not isinstance ( idx , Index ) : # pragma : no cover
from pandas . io . pickle import _unpickle_ar... |
def delete_group ( group_name , region = None , key = None , keyid = None , profile = None ) :
'''Delete a group policy .
CLI Example : :
. . code - block : : bash
salt myminion boto _ iam . delete _ group mygroup''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
if not conn :
return False
_group = get_group ( group_name , region , key , keyid , profile )
if not _group :
return True
try :
conn . delete_group ( group_name )
log . info ( 'Successfully deleted IAM group %s.' , grou... |
def state_machines_del_notification ( self , model , prop_name , info ) :
"""Relive models of closed state machine""" | if info [ 'method_name' ] == '__delitem__' :
state_machine_m = info [ "result" ]
try :
self . relieve_model ( state_machine_m )
except KeyError :
pass
self . clean_up_tabs ( ) |
def _process_execs ( self , contents , modulename , atype , mode = "insert" ) :
"""Extracts all the executable methods that belong to the type .""" | # We only want to look at text after the contains statement
match = self . RE_CONTAINS . search ( contents )
# It is possible for the type to not have any executables
if match is not None :
exectext = match . group ( "remainder" )
self . _process_execs_contents ( exectext , modulename , atype , mode ) |
def reason ( self , reason ) :
"""Sets the reason of this CreateRefundRequest .
A description of the reason for the refund . Default value : ` Refund via API `
: param reason : The reason of this CreateRefundRequest .
: type : str""" | if reason is None :
raise ValueError ( "Invalid value for `reason`, must not be `None`" )
if len ( reason ) > 192 :
raise ValueError ( "Invalid value for `reason`, length must be less than `192`" )
self . _reason = reason |
def update ( self , json_state ) :
"""Update the json data from a dictionary .
Only updates if it already exists in the device .""" | if self . _type in CONST . BINARY_SENSOR_TYPES :
self . _json_state [ 'status' ] = json_state [ 'status' ]
else :
self . _json_state . update ( { k : json_state [ k ] for k in json_state if self . _json_state . get ( k ) } ) |
def _collapse_by_bam_variantcaller ( samples ) :
"""Collapse regions to a single representative by BAM input , variant caller and batch .""" | by_bam = collections . OrderedDict ( )
for data in ( x [ 0 ] for x in samples ) :
work_bam = utils . get_in ( data , ( "combine" , "work_bam" , "out" ) , data . get ( "align_bam" ) )
variantcaller = get_variantcaller ( data )
if isinstance ( work_bam , list ) :
work_bam = tuple ( work_bam )
key ... |
def createDdbTable ( region = None , table = "credential-store" , ** kwargs ) :
'''create the secret store table in DDB in the specified region''' | session = get_session ( ** kwargs )
dynamodb = session . resource ( "dynamodb" , region_name = region )
if table in ( t . name for t in dynamodb . tables . all ( ) ) :
print ( "Credential Store table already exists" )
return
print ( "Creating table..." )
dynamodb . create_table ( TableName = table , KeySchema =... |
def audit_with_request ( ** kwargs ) :
"""use this decorator to audit an operation with a request as input variable""" | def wrap ( fn ) :
@ audit ( ** kwargs )
def operation ( parent_object , * args , ** kw ) :
return fn ( parent_object . request , * args , ** kw )
@ functools . wraps ( fn )
def advice_with_request ( the_request , * args , ** kw ) :
class ParentObject :
request = the_request
... |
def asRGB ( self ) :
"""Return image as RGB pixels . RGB colour images are passed
through unchanged ; greyscales are expanded into RGB
triplets ( there is a small speed overhead for doing this ) .
An alpha channel in the source image will raise an
exception .
The return values are as for the : meth : ` re... | width , height , pixels , meta = self . asDirect ( )
if meta [ 'alpha' ] :
raise Error ( "will not convert image with alpha channel to RGB" )
if not meta [ 'greyscale' ] :
return width , height , pixels , meta
meta [ 'greyscale' ] = False
typecode = 'BH' [ meta [ 'bitdepth' ] > 8 ]
def iterrgb ( ) :
for row... |
def find_inodes_in_use ( fds ) :
"""Find which of these inodes are in use , and give their open modes .
Does not count the passed fds as an use of the inode they point to ,
but if the current process has the same inodes open with different
file descriptors these will be listed .
Looks at / proc / * / fd and... | self_pid = os . getpid ( )
id_fd_assoc = collections . defaultdict ( list )
for fd in fds :
st = os . fstat ( fd )
id_fd_assoc [ ( st . st_dev , st . st_ino ) ] . append ( fd )
def st_id_candidates ( it ) : # map proc paths to stat identifiers ( devno and ino )
for proc_path in it :
try :
... |
def reload ( self , r = None , pr = None , timeout = None , basic_quorum = None , notfound_ok = None , head_only = False ) :
"""Reload the object from Riak . When this operation completes , the
object could contain new metadata and a new value , if the object
was updated in Riak since it was last retrieved .
... | self . client . get ( self , r = r , pr = pr , timeout = timeout , head_only = head_only )
return self |
def addSubprocess ( self , fds , name , factory ) :
"""Public method for _ addSubprocess .
Wraps reactor . adoptStreamConnection in
a simple DeferredLock to guarantee
workers play well together .""" | self . _lock . run ( self . _addSubprocess , self , fds , name , factory ) |
def add_token_with_limits ( self , token_address : TokenAddress , channel_participant_deposit_limit : TokenAmount , token_network_deposit_limit : TokenAmount , ) -> Address :
"""Register token of ` token _ address ` with the token network .
The limits apply for version 0.13.0 and above of raiden - contracts ,
s... | return self . _add_token ( token_address = token_address , additional_arguments = { '_channel_participant_deposit_limit' : channel_participant_deposit_limit , '_token_network_deposit_limit' : token_network_deposit_limit , } , ) |
def make_auc_structure ( score_structure ) :
"""calculates ROC data points and returns roc _ structure , a modified form of the score _ structure format
: param score _ structure : list [ ( id , best _ score , best _ query , status , net decoy count , net active count ) , . . . , ]
: return auc _ structure : li... | n = len ( [ x for x in score_structure if x [ 3 ] == '0' ] )
# Total no . of decoys
p = len ( [ x for x in score_structure if x [ 3 ] == '1' ] )
# Total no . of actives
auc_structure = [ ]
for mol in score_structure :
if n == 0 :
fpf = 0
else :
fpf = float ( mol [ 4 ] ) / n
if p == 0 :
... |
def call ( self , module , * args , ** kwargs ) :
'''Call an Ansible module by invoking it .
: param module : the name of the module .
: param args : Arguments to the module
: param kwargs : keywords to the module
: return :''' | module = self . _resolver . load_module ( module )
if not hasattr ( module , 'main' ) :
raise CommandExecutionError ( 'This module is not callable ' '(see "ansible.help {0}")' . format ( module . __name__ . replace ( 'ansible.modules.' , '' ) ) )
if args :
kwargs [ '_raw_params' ] = ' ' . join ( args )
js_args ... |
def preScale ( self , sx , sy ) :
"""Calculate pre scaling and replace current matrix .""" | self . a *= sx
self . b *= sx
self . c *= sy
self . d *= sy
return self |
def relative_redirect_n_times ( n ) :
"""Relatively 302 Redirects n times .
tags :
- Redirects
parameters :
- in : path
name : n
type : int
produces :
- text / html
responses :
302:
description : A redirection .""" | assert n > 0
response = app . make_response ( "" )
response . status_code = 302
if n == 1 :
response . headers [ "Location" ] = url_for ( "view_get" )
return response
response . headers [ "Location" ] = url_for ( "relative_redirect_n_times" , n = n - 1 )
return response |
def check_for_period_error ( data , period ) :
"""Check for Period Error .
This method checks if the developer is trying to enter a period that is
larger than the data set being entered . If that is the case an exception is
raised with a custom message that informs the developer that their period
is greater... | period = int ( period )
data_len = len ( data )
if data_len < period :
raise Exception ( "Error: data_len < period" ) |
def infer ( self , ob ) :
"""Add new observation to frame stack and infer policy .
Args :
ob : array of shape ( height , width , channels )
Returns :
logits and vf .""" | self . _add_to_stack ( ob )
logits , vf = self . infer_from_frame_stack ( self . _frame_stack )
return logits , vf |
def error_handler ( response , ** kwargs ) :
"""Error Handler to surface 4XX and 5XX errors .
Attached as a callback hook on the Request object .
Parameters
response ( requests . Response )
The HTTP response from an API request .
* * kwargs
Arbitrary keyword arguments .
Raises
ClientError ( ApiError... | if 400 <= response . status_code <= 499 :
message = response . json ( ) [ 'error_description' ] if 'error_description' in response . json ( ) else response . json ( ) [ 'error_detail' ]
raise ClientError ( response , message )
elif 500 <= response . status_code <= 599 :
raise ServerError ( response )
return... |
def update_db ( self , giver , receiverkarma ) :
"""Record a the giver of karma , the receiver of karma , and the karma
amount . Typically the count will be 1 , but it can be any positive or
negative integer .""" | for receiver in receiverkarma :
if receiver != giver :
urow = KarmaStatsTable ( ude ( giver ) , ude ( receiver ) , receiverkarma [ receiver ] )
self . db . session . add ( urow )
self . db . session . commit ( ) |
def get_current_track_info ( self ) :
"""Get information about the currently playing track .
Returns :
dict : A dictionary containing information about the currently
playing track : playlist _ position , duration , title , artist , album ,
position and an album _ art link .
If we ' re unable to return dat... | response = self . avTransport . GetPositionInfo ( [ ( 'InstanceID' , 0 ) , ( 'Channel' , 'Master' ) ] )
track = { 'title' : '' , 'artist' : '' , 'album' : '' , 'album_art' : '' , 'position' : '' }
track [ 'playlist_position' ] = response [ 'Track' ]
track [ 'duration' ] = response [ 'TrackDuration' ]
track [ 'uri' ] = ... |
def clearImg ( self ) :
"""Clears the current image""" | self . img . setImage ( np . array ( [ [ 0 ] ] ) )
self . img . image = None |
def logging_raslog_console ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
logging = ET . SubElement ( config , "logging" , xmlns = "urn:brocade.com:mgmt:brocade-ras" )
raslog = ET . SubElement ( logging , "raslog" )
console = ET . SubElement ( raslog , "console" )
console . text = kwargs . pop ( 'console' )
callback = kwargs . pop ( 'callback' , self . _cal... |
def _postgresql ( self , dbhost , dbport , dbname , dbuser , dbpass , dsn_style = None ) : # noqa
"""PostgreSQL psycopg2 driver accepts two syntaxes
Plus a string for . pgpass file""" | dsn = [ ]
if dsn_style is None or dsn_style == 'all' or dsn_style == 'keyvalue' :
dsnstr = "host='{0}' dbname='{2}' user='{3}' password='{4}'"
if dbport is not None :
dsnstr += " port='{1}'"
dsn . append ( dsnstr . format ( dbhost , dbport , dbname , dbuser , dbpass , ) )
if dsn_style == 'all' or ds... |
def calc_evi_inzp_v1 ( self ) :
"""Calculate interception evaporation and update the interception
storage accordingly .
Required control parameters :
| NHRU |
| Lnk |
| TRefT |
| TRefN |
Required flux sequence :
| EvPo |
Calculated flux sequence :
| EvI |
Updated state sequence :
| Inzp |
... | con = self . parameters . control . fastaccess
flu = self . sequences . fluxes . fastaccess
sta = self . sequences . states . fastaccess
for k in range ( con . nhru ) :
if con . lnk [ k ] in ( WASSER , FLUSS , SEE ) :
flu . evi [ k ] = flu . evpo [ k ]
sta . inzp [ k ] = 0.
else :
flu . ... |
def stopPolitely ( self , disconnect = False ) :
"""Delete all active ROSpecs . Return a Deferred that will be called
when the DELETE _ ROSPEC _ RESPONSE comes back .""" | logger . info ( 'stopping politely' )
if disconnect :
logger . info ( 'will disconnect when stopped' )
self . disconnecting = True
self . sendMessage ( { 'DELETE_ACCESSSPEC' : { 'Ver' : 1 , 'Type' : 41 , 'ID' : 0 , 'AccessSpecID' : 0 # all AccessSpecs
} } )
self . setState ( LLRPClient . STATE_SENT_DELETE_ACCES... |
def attach_tcp_service ( cls , tcp_service : TCPService ) :
"""Attaches a service for hosting
: param tcp _ service : A TCPService instance""" | if cls . _services [ '_tcp_service' ] is None :
cls . _services [ '_tcp_service' ] = tcp_service
cls . _set_bus ( tcp_service )
else :
warnings . warn ( 'TCP service is already attached' ) |
def validate_signature ( self , filename ) :
"""Returns True if a valid signature is present for filename""" | if not GPG_PRESENT :
return False
sigfilename = filename + '.sig'
try :
with open ( sigfilename ) :
pass
except IOError : # Signature file does not exist
return False
# Check if the sig is valid for the sigfile
# TODO : Check for whitespace in filepaths
return verify ( sigfilename , filename ) |
def print_raw_data ( raw_data , start_index = 0 , limit = 200 , flavor = 'fei4b' , index_offset = 0 , select = None , tdc_trig_dist = False , trigger_data_mode = 0 ) :
"""Printing FEI4 raw data array for debugging .""" | if not select :
select = [ 'DH' , 'TW' , "AR" , "VR" , "SR" , "DR" , 'TDC' , 'UNKNOWN FE WORD' , 'UNKNOWN WORD' ]
total_words = 0
for index in range ( start_index , raw_data . shape [ 0 ] ) :
dw = FEI4Record ( raw_data [ index ] , chip_flavor = flavor , tdc_trig_dist = tdc_trig_dist , trigger_data_mode = trigge... |
def bzpopmax ( self , keys , timeout = 0 ) :
"""ZPOPMAX a value off of the first non - empty sorted set
named in the ` ` keys ` ` list .
If none of the sorted sets in ` ` keys ` ` has a value to ZPOPMAX ,
then block for ` ` timeout ` ` seconds , or until a member gets added
to one of the sorted sets .
If ... | if timeout is None :
timeout = 0
keys = list_or_args ( keys , None )
keys . append ( timeout )
return self . execute_command ( 'BZPOPMAX' , * keys ) |
def user_assigned_policies ( user ) :
"""Return sequence of policies assigned to a user ( or the anonymous
user is ` ` user ` ` is ` ` None ` ` ) . ( Also installed as
` ` assigned _ policies ` ` method on ` ` User ` ` model .""" | key = user_cache_key ( user )
cached = cache . get ( key )
if cached is not None :
return cached
if user is None :
pset = PermissionSet . objects . filter ( anonymous_user = True ) . first ( )
else :
pset = user . permissionset . first ( )
if pset is None :
return [ ]
res = [ ]
skip_role_policies = Fals... |
def tx_tmpdir ( base_dir , rollback_dirpath ) :
"""Context manager to create and remove a transactional temporary directory .""" | # tmp _ dir _ base = join ( base _ dir , ' tx ' , str ( uuid . uuid4 ( ) ) )
# unique _ attempts = 0
# while os . path . exists ( tmp _ dir _ base ) :
# if unique _ attempts > 5:
# break
# tmp _ dir _ base = join ( base _ dir , ' tx ' , str ( uuid . uuid4 ( ) ) )
# time . sleep ( 1)
# unique _ attempts + = 1
# if base ... |
def to_html ( self , table_width = 5 ) :
"""Write the program information to HTML code , which can be saved ,
printed and brought to the gym .
Parameters
table _ width
The table with of the HTML code .
Returns
string
HTML code .""" | env = self . jinja2_environment
template = env . get_template ( self . TEMPLATE_NAMES [ 'html' ] )
return template . render ( program = self , table_width = table_width ) |
def count_unique_mapped_reads ( self , file_name , paired_end ) :
"""For a bam or sam file with paired or or single - end reads , returns the
number of mapped reads , counting each read only once , even if it appears
mapped at multiple locations .
: param str file _ name : name of reads file
: param bool pa... | _ , ext = os . path . splitext ( file_name )
ext = ext . lower ( )
if ext == ".sam" :
param = "-S -F4"
elif ext == "bam" :
param = "-F4"
else :
raise ValueError ( "Not a SAM or BAM: '{}'" . format ( file_name ) )
if paired_end :
r1 = self . samtools_view ( file_name , param = param + " -f64" , postpend ... |
def upload_to_mugshot ( instance , filename ) :
"""Uploads a mugshot for a user to the ` ` USERENA _ MUGSHOT _ PATH ` ` and saving it
under unique hash for the image . This is for privacy reasons so others
can ' t just browse through the mugshot directory .""" | extension = filename . split ( '.' ) [ - 1 ] . lower ( )
salt , hash = generate_sha1 ( instance . pk )
path = userena_settings . USERENA_MUGSHOT_PATH % { 'username' : instance . user . username , 'id' : instance . user . id , 'date' : instance . user . date_joined , 'date_now' : get_datetime_now ( ) . date ( ) }
return... |
def coord_shift ( xyz , box ) :
"""Ensures that coordinates are - L / 2 , L / 2
Checks if coordinates are - L / 2 , L / 2 and then shifts coordinates
if necessary . For example , if coordinates are 0 , L , then a shift
is applied to move coordinates to - L / 2 , L / 2 . If a shift is not
necessary , the poi... | box = np . asarray ( box )
assert box . shape == ( 3 , )
box_max = box / 2.
box_min = - box_max
# Shift all atoms
if np . greater ( xyz , box_max ) . any ( ) :
xyz -= box_max
elif np . less ( xyz , box_min ) . any ( ) :
xyz += box_max
return xyz |
def getattrs ( value , attrs , default = _no_default ) :
"""Perform a chained application of ` ` getattr ` ` on ` ` value ` ` with the values
in ` ` attrs ` ` .
If ` ` default ` ` is supplied , return it if any of the attribute lookups fail .
Parameters
value : object
Root of the lookup chain .
attrs : ... | try :
for attr in attrs :
value = getattr ( value , attr )
except AttributeError :
if default is _no_default :
raise
value = default
return value |
def _layout_for_domfuzz ( self , path ) :
"""Update directory to work with DOMFuzz
@ type path : str
@ param path : A string representation of the fuzzmanager config path""" | old_dir = os . getcwd ( )
os . chdir ( os . path . join ( path ) )
try :
os . mkdir ( 'dist' )
link_name = os . path . join ( 'dist' , 'bin' )
if self . _platform . system == 'Darwin' and self . _target == 'firefox' :
ff_loc = glob . glob ( '*.app/Contents/MacOS/firefox' )
assert len ( ff_lo... |
def percentage ( self ) :
"""Returns the percentage of votes cast for this poll option in
relation to all of its poll ' s other options .""" | total_vote_count = self . poll . vote_count
if total_vote_count :
return self . vote_count * 100.0 / total_vote_count
return 0 |
def element_data_from_sym ( sym ) :
'''Obtain elemental data given an elemental symbol
The given symbol is not case sensitive
An exception is thrown if the symbol is not found''' | sym_lower = sym . lower ( )
if sym_lower not in _element_sym_map :
raise KeyError ( 'No element data for symbol \'{}\'' . format ( sym ) )
return _element_sym_map [ sym_lower ] |
def _set_fru ( self , v , load = False ) :
"""Setter method for fru , mapped from YANG variable / system _ monitor _ mail / fru ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ fru is considered as a private
method . Backends looking to populate this vari... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = fru . fru , is_container = 'container' , presence = False , yang_name = "fru" , rest_name = "fru" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { ... |
def enter_proc ( self , lineno ) :
"""Enters ( pushes ) a new context""" | self . local_labels . append ( { } )
# Add a new context
self . scopes . append ( lineno )
__DEBUG__ ( 'Entering scope level %i at line %i' % ( len ( self . scopes ) , lineno ) ) |
def update_field_names ( self , data , matching ) :
"""This method updates the names of the fields according to matching
: param data : original Pandas dataframe
: param matching : dictionary of matchings between old and new values
: type data : pandas . DataFrame
: type matching : dictionary
: returns : ... | for key in matching . keys ( ) :
if key in data . columns :
data . rename ( columns = { key : matching [ key ] } )
return data |
def normalize_uri_path_component ( path_component ) :
"""normalize _ uri _ path _ component ( path _ component ) - > str
Normalize the path component according to RFC 3986 . This performs the
following operations :
* Alpha , digit , and the symbols ' - ' , ' . ' , ' _ ' , and ' ~ ' ( unreserved
characters )... | result = BytesIO ( )
i = 0
path_component = path_component . encode ( "utf-8" )
while i < len ( path_component ) :
c = indexbytes ( path_component , i )
if c in _rfc3986_unreserved :
result . write ( int2byte ( c ) )
i += 1
elif c == _ascii_percent : # percent , ' % ' , 0x25 , 37
if ... |
def timing ( self ) :
"""Estimates timing information for the current setup . You should
run a check on the instrument parameters before calling this .
Returns : ( expTime , deadTime , cycleTime , dutyCycle )
expTime : exposure time per frame ( seconds )
deadTime : dead time per frame ( seconds )
cycleTim... | # drift mode y / n ?
isDriftMode = self . isDrift ( )
# FF y / n ?
isFF = self . isFF ( )
# Set the readout speed
readSpeed = self . readSpeed ( )
if readSpeed == 'Fast' and self . dummy ( ) :
video = VIDEO_FAST
elif readSpeed == 'Slow' and self . dummy ( ) :
video = VIDEO_SLOW
elif not self . dummy ( ) :
v... |
def create ( self , to , status_callback = values . unset , application_sid = values . unset , max_price = values . unset , provide_feedback = values . unset , validity_period = values . unset , force_delivery = values . unset , smart_encoded = values . unset , interactive_data = values . unset , force_opt_in = values ... | data = values . of ( { 'To' : to , 'From' : from_ , 'MessagingServiceSid' : messaging_service_sid , 'Body' : body , 'MediaUrl' : serialize . map ( media_url , lambda e : e ) , 'StatusCallback' : status_callback , 'ApplicationSid' : application_sid , 'MaxPrice' : max_price , 'ProvideFeedback' : provide_feedback , 'Valid... |
def entropy_bits ( lst : Union [ List [ Union [ int , str , float , complex ] ] , Tuple [ Union [ int , str , float , complex ] ] ] ) -> float :
"""Calculate the entropy of a wordlist or a numerical range .
Keyword arguments :
lst - - A wordlist as list or tuple , or a numerical range as a list :
( minimum , ... | if not isinstance ( lst , ( tuple , list ) ) :
raise TypeError ( 'lst must be a list or a tuple' )
size = len ( lst )
if ( size == 2 and isinstance ( lst [ 0 ] , ( int , float ) ) and isinstance ( lst [ 1 ] , ( int , float ) ) ) :
return calc_entropy_bits_nrange ( lst [ 0 ] , lst [ 1 ] )
return calc_entropy_bit... |
def get_settings ( self ) :
"""Get settings .""" | postgame = self . get_postgame ( )
return { 'type' : ( self . _header . lobby . game_type_id , self . _header . lobby . game_type ) , 'difficulty' : ( self . _header . scenario . game_settings . difficulty_id , self . _header . scenario . game_settings . difficulty ) , 'population_limit' : self . _header . lobby . popu... |
def only ( self , * keys ) :
"""Get the items with the specified keys .
: param keys : The keys to keep
: type keys : tuple
: rtype : Collection""" | items = [ ]
for key , value in enumerate ( self . items ) :
if key in keys :
items . append ( value )
return self . __class__ ( items ) |
def _upsampling ( lr_array , rescale , reference_shape , interp = 'linear' ) :
"""Upsample the low - resolution array to the original high - resolution grid
: param lr _ array : Low - resolution array to be upsampled
: param rescale : Rescale factor for rows / columns
: param reference _ shape : Original size... | hr_shape = reference_shape + ( 1 , )
lr_shape = lr_array . shape + ( 1 , )
if rescale is None :
return lr_array . reshape ( lr_shape )
out_array = scipy . ndimage . interpolation . zoom ( lr_array . reshape ( lr_shape ) , ( 1.0 , ) + tuple ( 1 / x for x in rescale ) + ( 1.0 , ) , output = lr_array . dtype , order =... |
def from_object ( self , obj : Union [ str , Any ] ) -> None :
"""Load values from an object .""" | if isinstance ( obj , str ) :
obj = importer . import_object_str ( obj )
for key in dir ( obj ) :
if key . isupper ( ) :
value = getattr ( obj , key )
self . _setattr ( key , value )
logger . info ( "Config is loaded from object: %r" , obj ) |
def to_filename ( data , mask = DEFAULT_PAPERS_FILENAME_MASK , extra_formatters = None ) :
"""Convert a bibtex entry to a formatted filename according to a given mask .
. . note : :
Available formatters out of the box are :
- ` ` journal ` `
- ` ` title ` `
- ` ` year ` `
- ` ` first ` ` for the first a... | # Handle default argument
if extra_formatters is None :
extra_formatters = { }
entry = data . entries [ 0 ]
authors = re . split ( ' and ' , entry [ 'author' ] )
formatters = { "journal" : "" , "title" : "" , "year" : "" , "first" : "" , "last" : "" , "authors" : "" , "arxiv_version" : "" }
formatters [ "journal" ]... |
def certificate_rabbitmq ( self ) :
"""Gets the Certificate RabbitMQ API client .
Returns :
CertificateRabbitMQ :""" | if not self . __certificate_rabbitmq :
self . __certificate_rabbitmq = CertificateRabbitMQ ( self . __connection )
return self . __certificate_rabbitmq |
def parse_string_to_constructor ( ctor_string ) :
"""Returns a callable which corresponds to the constructor string .
Various modules ( eg , ConvNet2D ) take constructor arguments which are
callables , indicating a submodule to build . These can be passed as
actual constructors , eg ` snt . LayerNorm ` , howe... | orig_ctor_string = ctor_string
if "." not in ctor_string : # No module specified - assume part of Sonnet
ctor_string = "sonnet." + ctor_string
if ctor_string . startswith ( "snt." ) : # Replace common short name with full name
ctor_string = "sonnet." + ctor_string [ len ( "snt." ) : ]
# Cannot just use importli... |
def handle_walk ( self , listener : TreeListener , tree : Union [ ast . Node , dict , list ] ) -> None :
"""Handles tree walking , has to account for dictionaries and lists
: param listener : listener that reacts to walked events
: param tree : the tree to walk
: return : None""" | if isinstance ( tree , ast . Node ) :
self . walk ( listener , tree )
elif isinstance ( tree , dict ) :
for k in tree . keys ( ) :
self . handle_walk ( listener , tree [ k ] )
elif isinstance ( tree , list ) :
for i in range ( len ( tree ) ) :
self . handle_walk ( listener , tree [ i ] )
els... |
def _get_fieldnames ( item ) :
"""Return fieldnames of either a namedtuple or GOEnrichmentRecord .""" | if hasattr ( item , "_fldsdefprt" ) : # Is a GOEnrichmentRecord
return item . get_prtflds_all ( )
if hasattr ( item , "_fields" ) : # Is a namedtuple
return item . _fields |
def google_news_search ( self , query , category_label , num = 50 ) :
'''Searches Google News .
NOTE : Official Google News API is deprecated https : / / developers . google . com / news - search / ? hl = en
NOTE : Google limits the maximum number of documents per query to 100.
Use multiple related queries to... | url = 'https://news.google.com/news?hl=en&q=' + self . _encode_query ( query ) + '&num=' + str ( num ) + '&output=rss'
rss = feedparser . parse ( url )
entries = rss [ 'entries' ]
articles = [ ]
for entry in entries :
link = entry [ 'link' ]
articles . append ( ( category_label , link ) )
return articles |
def _create_verify_email_token_url ( self , base_url = None , view_class = None ) :
"""To create a verify email token url
: param user : ( object ) AuthUser
: param base _ url : a base _ url to use instead of the native one
: param view _ class : ( obj ) the view class , to allow build the url
: return : st... | view = view_class or views . auth . Login
endpoint = getattr ( view , "verify_email" )
action = "verify-email"
expires_in = __options__ . get ( "verify_email_token_ttl" ) or ( 60 * 24 )
action_token = self . create_action_token ( action , expires_in )
signed_data = self . sign_data ( action , expires_in = expires_in )
... |
def ask_folder ( message = 'Select folder.' , default = '' , title = '' ) :
"""A dialog to get a directory name .
Returns the name of a directory , or None if user chose to cancel .
If the " default " argument specifies a directory name , and that
directory exists , then the dialog box will start with that di... | return backend_api . opendialog ( "ask_folder" , dict ( message = message , default = default , title = title ) ) |
def processPrepare ( self , prepare : Prepare , sender : str ) -> None :
"""Validate and process the PREPARE specified .
If validation is successful , create a COMMIT and broadcast it .
: param prepare : a PREPARE msg
: param sender : name of the node that sent the PREPARE""" | key = ( prepare . viewNo , prepare . ppSeqNo )
self . logger . debug ( "{} received PREPARE{} from {}" . format ( self , key , sender ) )
# TODO move this try / except up higher
try :
if self . validatePrepare ( prepare , sender ) :
self . addToPrepares ( prepare , sender )
self . stats . inc ( TPCS... |
def _select_channels ( data , channels ) :
"""Select channels .
Parameters
data : instance of ChanTime
data with all the channels
channels : list
channels of interest
Returns
instance of ChanTime
data with only channels of interest
Notes
This function does the same as wonambi . trans . select , ... | output = data . _copy ( )
chan_list = list ( data . axis [ 'chan' ] [ 0 ] )
idx_chan = [ chan_list . index ( i_chan ) for i_chan in channels ]
output . data [ 0 ] = data . data [ 0 ] [ idx_chan , : ]
output . axis [ 'chan' ] [ 0 ] = asarray ( channels )
return output |
def length_of_geographical_area_code ( numobj ) :
"""Return length of the geographical area code for a number .
Gets the length of the geographical area code from the PhoneNumber object
passed in , so that clients could use it to split a national significant
number into geographical area code and subscriber n... | metadata = PhoneMetadata . metadata_for_region ( region_code_for_number ( numobj ) , None )
if metadata is None :
return 0
# If a country doesn ' t use a national prefix , and this number doesn ' t have
# an Italian leading zero , we assume it is a closed dialling plan with no
# area codes .
if metadata . national_... |
def _pandas_df_to_dendropy_tree ( df , taxon_col = 'uid' , taxon_annotations = [ ] , node_col = 'uid' , node_annotations = [ ] , branch_lengths = True , ) :
"""Turn a phylopandas dataframe into a dendropy tree .
Parameters
df : DataFrame
DataFrame containing tree data .
taxon _ col : str ( optional )
Colu... | if isinstance ( taxon_col , str ) is False :
raise Exception ( "taxon_col must be a string." )
if isinstance ( node_col , str ) is False :
raise Exception ( "taxon_col must be a string." )
# Construct a list of nodes from dataframe .
taxon_namespace = dendropy . TaxonNamespace ( )
nodes = { }
for idx in df . in... |
def split_styles ( mark ) :
"""get shared styles""" | markers = [ mark . _table [ key ] for key in mark . _marker ] [ 0 ]
nstyles = [ ]
for m in markers : # # fill and stroke are already rgb ( ) since already in markers
msty = toyplot . style . combine ( { "fill" : m . mstyle [ 'fill' ] , "stroke" : m . mstyle [ 'stroke' ] , "opacity" : m . mstyle [ "fill-opacity" ] ,... |
def save_assessment ( self , assessment_form , * args , ** kwargs ) :
"""Pass through to provider AssessmentAdminSession . update _ assessment""" | # Implemented from kitosid template for -
# osid . resource . ResourceAdminSession . update _ resource
if assessment_form . is_for_update ( ) :
return self . update_assessment ( assessment_form , * args , ** kwargs )
else :
return self . create_assessment ( assessment_form , * args , ** kwargs ) |
def html_overall_stat ( overall_stat , digit = 5 , overall_param = None , recommended_list = ( ) ) :
"""Return HTML report file overall stat .
: param overall _ stat : overall stat
: type overall _ stat : dict
: param digit : scale ( the number of digits to the right of the decimal point in a number . )
: t... | result = ""
result += "<h2>Overall Statistics : </h2>\n"
result += '<table style="border:1px solid black;border-collapse: collapse;">\n'
overall_stat_keys = sorted ( overall_stat . keys ( ) )
if isinstance ( overall_param , list ) :
if set ( overall_param ) <= set ( overall_stat_keys ) :
overall_stat_keys =... |
def _get_cl_dependency_code ( self ) :
"""Get the CL code for all the CL code for all the dependencies .
Returns :
str : The CL code with the actual code .""" | code = ''
for d in self . _dependencies :
code += d . get_cl_code ( ) + "\n"
return code |
def connectionMap ( self , scene , nodes ) :
"""Generates a mapping for the nodes to each other based on their
connections .
: param nodes | [ < XNode > , . . ]
: return { < XNode > : ( [ < XNode > input , . . ] , [ < XNode > output , . . ] ) , . . }""" | output = { }
connections = scene . connections ( )
for node in nodes :
inputs = [ ]
outputs = [ ]
for connection in connections :
in_node = connection . inputNode ( )
out_node = connection . outputNode ( )
if node == in_node :
inputs . append ( out_node )
elif nod... |
def _color_level ( str_ , level ) :
"""Return the string wrapped with the appropriate styling for the message
level . The styling will be determined based on the rez configuration .
Args :
str _ ( str ) : The string to be wrapped .
level ( str ) : The message level . Should be one of ' critical ' , ' error ... | fore_color , back_color , styles = _get_style_from_config ( level )
return _color ( str_ , fore_color , back_color , styles ) |
def encipher_vigenere ( plaintext , plain_vocab , key ) :
"""Encrypt plain text with given key .
Args :
plaintext ( list of list of Strings ) : a list of plain text to encrypt .
plain _ vocab ( list of Integer ) : unique vocabularies being used .
key ( list of Integer ) : key to encrypt cipher using Vigener... | ciphertext = [ ]
# generate Vigenere table
layers = [ ShiftEncryptionLayer ( plain_vocab , i ) for i in range ( len ( plain_vocab ) ) ]
for i , sentence in enumerate ( plaintext ) :
cipher_sentence = [ ]
for j , character in enumerate ( sentence ) :
key_idx = key [ j % len ( key ) ]
encrypted_ch... |
def implement_switch_disconnector ( mv_grid , node1 , node2 ) :
"""Install switch disconnector in grid topology
The graph that represents the grid ' s topology is altered in such way that
it explicitly includes a switch disconnector .
The switch disconnector is always located at ` ` node1 ` ` . Technically , ... | # Get disconnecting point ' s location
line = mv_grid . graph . edge [ node1 ] [ node2 ] [ 'line' ]
length_sd_line = .75e-3
# in km
x_sd = node1 . geom . x + ( length_sd_line / line . length ) * ( node1 . geom . x - node2 . geom . x )
y_sd = node1 . geom . y + ( length_sd_line / line . length ) * ( node1 . geom . y - n... |
def load_stencil_set ( self , stencilset_name ) :
"""Return the Stencil Set from this template pack .""" | if stencilset_name not in self . _stencil_sets :
if stencilset_name not in self . manifest [ 'stencil_sets' ] . keys ( ) :
raise exc . FastfoodStencilSetNotListed ( "Stencil set '%s' not listed in %s under stencil_sets." % ( stencilset_name , self . manifest_path ) )
stencil_path = os . path . join ( se... |
def decrypt_data ( self , name , ciphertext , context = "" , nonce = "" , batch_input = None , mount_point = DEFAULT_MOUNT_POINT ) :
"""Decrypt the provided ciphertext using the named key .
Supported methods :
POST : / { mount _ point } / decrypt / { name } . Produces : 200 application / json
: param name : S... | params = { 'ciphertext' : ciphertext , 'context' : context , 'nonce' : nonce , 'batch_input' : batch_input , }
api_path = '/v1/{mount_point}/decrypt/{name}' . format ( mount_point = mount_point , name = name , )
response = self . _adapter . post ( url = api_path , json = params , )
return response . json ( ) |
def getResults ( uri ) :
'''Method that recovers the text for each result in infobel . com
: param uri : Infobel uri
: return : A list of textual information to be processed''' | # Using i3visio browser to avoid certain issues . . .
i3Browser = browser . Browser ( )
data = i3Browser . recoverURL ( uri )
# Strings to be searched
regExp = "<!-- Results -->(.*)<!-- /Results -->"
# re . DOTALL is needed to match any character INCLUDING \ n
results = re . findall ( regExp , data , re . DOTALL )
retu... |
def plot_sample_rate_compare ( data_dict , file_name = None ) :
"""Brief
Is a plotting function that shows a sequence of ECG plots , demonstrating the relevance of
choosing a wright sampling rate .
Description
Function intended to generate a Bokeh figure with Nx2 format , being N the number of keys of
' d... | # Generation of the HTML file where the plot will be stored .
# file _ name = _ generate _ bokeh _ file ( file _ name )
nbr_rows = len ( list ( data_dict . keys ( ) ) )
# List that store the figure handler .
list_figures = plot ( [ [ ] ] * nbr_rows * 2 , [ [ ] ] * nbr_rows * 2 , y_axis_label = "Raw Data" , x_axis_label... |
def message_remove ( request , undo = False ) :
"""A ` ` POST ` ` to remove messages .
: param undo :
A Boolean that if ` ` True ` ` unremoves messages .
POST can have the following keys :
` ` message _ pks ` `
List of message id ' s that should be deleted .
` ` next ` `
String containing the URI whic... | message_pks = request . POST . getlist ( 'message_pks' )
redirect_to = request . GET . get ( REDIRECT_FIELD_NAME , request . POST . get ( REDIRECT_FIELD_NAME , False ) )
if message_pks : # Check that all values are integers .
valid_message_pk_list = set ( )
for pk in message_pks :
try :
vali... |
def get_form ( self , form_class ) :
"""Returns an instance of the form to be used in this view .""" | if not hasattr ( self , '_form' ) :
kwargs = self . get_form_kwargs ( )
self . _form = form_class ( ** kwargs )
return self . _form |
def bam2fastq ( self , input_bam , output_fastq , output_fastq2 = None , unpaired_fastq = None ) :
"""Create command to convert BAM ( s ) to FASTQ ( s ) .
: param str input _ bam : Path to sequencing reads file to convert
: param output _ fastq : Path to FASTQ to write
: param output _ fastq2 : Path to ( R2 )... | self . _ensure_folders ( output_fastq , output_fastq2 , unpaired_fastq )
cmd = self . tools . java + " -Xmx" + self . pm . javamem
cmd += " -jar " + self . tools . picard + " SamToFastq"
cmd += " INPUT={0}" . format ( input_bam )
cmd += " FASTQ={0}" . format ( output_fastq )
if output_fastq2 is not None and unpaired_fa... |
def pexpireat ( self , name , when ) :
"""Set an expire flag on key ` ` name ` ` . ` ` when ` ` can be represented
as an integer representing unix time in milliseconds ( unix time * 1000)
or a Python datetime object .""" | with self . pipe as pipe :
return pipe . pexpireat ( self . redis_key ( name ) , when ) |
def _bin_update_items ( self , items , replace_at_most_one , replacements , leftovers ) :
"""< replacements and < leftovers > are modified directly , ala pass by
reference .""" | for key , value in items : # If there are existing items with key < key > that have yet to be
# marked for replacement , mark that item ' s value to be replaced by
# < value > by appending it to < replacements > .
if key in self and key not in replacements :
replacements [ key ] = [ value ]
elif ( key i... |
def add_edge_attributes ( self , edge , attrs ) :
"""Append a sequence of attributes to the given edge
@ type edge : edge
@ param edge : One edge .
@ type attrs : tuple
@ param attrs : Node attributes specified as a sequence of tuples in the form ( attribute , value ) .""" | for attr in attrs :
self . add_edge_attribute ( edge , attr ) |
def run ( self , ** kwargs ) :
"""Execute the scheduler .
Returns :
` None `""" | if not super ( ) . run ( ** kwargs ) :
return
if kwargs [ 'list' ] :
self . log . info ( '--- List of Scheduler Modules ---' )
for name , scheduler in list ( self . scheduler_plugins . items ( ) ) :
if self . active_scheduler == name :
self . log . info ( '{} (active)' . format ( name ) ... |
def effective_nsamples ( self ) :
"""The effective number of samples post burn - in that the sampler has
acquired so far .""" | try :
act = numpy . array ( list ( self . acts . values ( ) ) ) . max ( )
except ( AttributeError , TypeError ) :
act = numpy . inf
if self . burn_in is None :
nperwalker = max ( int ( self . niterations // act ) , 1 )
elif self . burn_in . is_burned_in :
nperwalker = int ( ( self . niterations - self .... |
def rmnode ( path : str ) :
"""Forcibly remove file or directory tree at ` path ` .
Fail silently if base dir doesn ' t exist .""" | if isdir ( path ) :
rmtree ( path )
elif isfile ( path ) :
os . remove ( path ) |
def make_directory_entry ( d ) :
"""Create a directory entry that conforms to the format of the Desktop Entry
Specification by freedesktop . org . See :
http : / / freedesktop . org / Standards / desktop - entry - spec
These should work for both KDE and Gnome2
An entry is a . directory file that includes th... | assert d [ 'path' ] . endswith ( '.directory' )
# default values
d . setdefault ( 'comment' , '' )
d . setdefault ( 'icon' , '' )
fo = open ( d [ 'path' ] , "w" )
fo . write ( """\
[Desktop Entry]
Type=Directory
Encoding=UTF-8
Name=%(name)s
Comment=%(comment)s
Icon=%(icon)s
""" % d )
fo . close ( ) |
def QA_SU_save_etf_min ( engine , client = DATABASE ) :
"""save etf _ min
Arguments :
engine { [ type ] } - - [ description ]
Keyword Arguments :
client { [ type ] } - - [ description ] ( default : { DATABASE } )""" | engine = select_save_engine ( engine )
engine . QA_SU_save_etf_min ( client = client ) |
def get_rows_by_cols ( self , matching_dict ) :
"""Return all rows where the cols match the elements given in the matching _ dict
Parameters
matching _ dict : : obj : ' dict '
Desired dictionary of col values .
Returns
: obj : ` list `
A list of rows that satisfy the matching _ dict""" | result = [ ]
for i in range ( self . num_rows ) :
row = self . _table [ i + 1 ]
matching = True
for key , val in matching_dict . items ( ) :
if row [ key ] != val :
matching = False
break
if matching :
result . append ( row )
return result |
def version ( self ) :
"""Return the build date of the gentoo container .""" | try :
_version = ( curl [ Gentoo . _LATEST_TXT ] | awk [ 'NR==2{print}' ] | cut [ "-f2" , "-d=" ] ) ( ) . strip ( )
_version = datetime . utcfromtimestamp ( int ( _version ) ) . strftime ( "%Y-%m-%d" )
except ProcessExecutionError as proc_ex :
_version = "unknown"
LOG . error ( "Could not determine time... |
def map_single_end ( credentials , instance_config , instance_name , script_dir , index_dir , fastq_file , output_dir , num_threads = None , seed_start_lmax = None , mismatch_nmax = None , multimap_nmax = None , splice_min_overhang = None , out_mult_nmax = None , sort_bam = True , keep_unmapped = False , self_destruct ... | if sort_bam :
out_sam_type = 'BAM SortedByCoordinate'
else :
out_sam_type = 'BAM Unsorted'
# template expects a list of FASTQ files
fastq_files = fastq_file
if isinstance ( fastq_files , ( str , _oldstr ) ) :
fastq_files = [ fastq_file ]
template = _TEMPLATE_ENV . get_template ( os . path . join ( 'map_sing... |
def transfer ( self , data ) :
"""Transfers data over SPI .
Arguments :
data : The data to transfer .
Returns :
The data returned by the SPI device .""" | settings = self . transfer_settings
settings . spi_tx_size = len ( data )
self . transfer_settings = settings
response = ''
for i in range ( 0 , len ( data ) , 60 ) :
response += self . sendCommand ( commands . SPITransferCommand ( data [ i : i + 60 ] ) ) . data
time . sleep ( 0.01 )
while len ( response ) < le... |
def upload ( client , source_dir ) :
"""Upload images to play store .
The function will iterate through source _ dir and upload all matching
image _ types found in folder herachy .""" | print ( '' )
print ( 'upload images' )
print ( '-------------' )
base_image_folders = [ os . path . join ( source_dir , 'images' , x ) for x in image_types ]
for type_folder in base_image_folders :
if os . path . exists ( type_folder ) :
image_type = os . path . basename ( type_folder )
langfolders ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.