signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def bed ( args ) :
"""% prog bed binfile fastafile
Write bed files where the bases have at least certain depth .""" | p = OptionParser ( bed . __doc__ )
p . add_option ( "-o" , dest = "output" , default = "stdout" , help = "Output file name [default: %default]" )
p . add_option ( "--cutoff" , dest = "cutoff" , default = 10 , type = "int" , help = "Minimum read depth to report intervals [default: %default]" )
opts , args = p . parse_ar... |
def daylight ( self , date = None , local = True , use_elevation = True ) :
"""Calculates the daylight time ( the time between sunrise and sunset )
: param date : The date for which to calculate daylight .
If no date is specified then the current date will be used .
: type date : : class : ` ~ datetime . date... | if local and self . timezone is None :
raise ValueError ( "Local time requested but Location has no timezone set." )
if self . astral is None :
self . astral = Astral ( )
if date is None :
date = datetime . date . today ( )
elevation = self . elevation if use_elevation else 0
start , end = self . astral . d... |
def after_request ( response ) :
"""Modifies the response object prior to sending it to the client . Used to add CORS headers to the request
Args :
response ( response ) : Flask response object
Returns :
` None `""" | response . headers . add ( 'Access-Control-Allow-Origin' , '*' )
response . headers . add ( 'Access-Control-Allow-Headers' , 'Content-Type,Authorization' )
response . headers . add ( 'Access-Control-Allow-Methods' , 'GET,PUT,POST,DELETE' )
return response |
def set_callback ( self , func ) :
"""Sets ' callback ' parameter . If supplied , the response will use the JSONP format with a callback of the given name
: param func : A string containing the name of the callback function
: raises : TwitterSearchException""" | if isinstance ( func , str if py3k else basestring ) and func :
self . arguments . update ( { 'callback' : '%s' % func } )
else :
raise TwitterSearchException ( 1006 ) |
def on_server_start ( self ) :
"""Service run loop function .
Run the desired docker container with parameters and start parsing the monitored file for alerts .""" | self . _container = self . _docker_client . containers . run ( self . docker_image_name , detach = True , ** self . docker_params )
self . signal_ready ( )
for log_line in self . get_lines ( ) :
try :
alert_dict = self . parse_line ( log_line )
if alert_dict :
self . add_alert_to_queue (... |
def dms_maker ( self , force_rerun = False ) :
"""Create surface representation ( dms file ) of receptor
Args :
force _ rerun ( bool ) : If method should be rerun even if output file exists""" | log . debug ( '{}: running surface representation maker...' . format ( self . id ) )
if not self . receptorpdb_path :
return ValueError ( 'Please run protein_only_and_noH' )
dms = op . join ( self . dock_dir , '{}_receptor.dms' . format ( self . id ) )
if ssbio . utils . force_rerun ( flag = force_rerun , outfile =... |
def get_tags_users ( self , id_ ) :
"""Get a particular user which are tagged based on the id _""" | return _get_request ( _TAGS_USERS . format ( c_api = _C_API_BEGINNING , api = _API_VERSION , id_ = id_ , at = self . access_token ) ) |
def htmlDocDump ( self , f ) :
"""Dump an HTML document to an open FILE .""" | ret = libxml2mod . htmlDocDump ( f , self . _o )
return ret |
def search ( self , query , fetch_messages = False , thread_limit = 5 , message_limit = 5 ) :
"""Searches for messages in all threads
: param query : Text to search for
: param fetch _ messages : Whether to fetch : class : ` models . Message ` objects or IDs only
: param thread _ limit : Max . number of threa... | data = { "query" : query , "snippetLimit" : thread_limit }
j = self . _post ( self . req_url . SEARCH_MESSAGES , data , fix_request = True , as_json = True )
result = j [ "payload" ] [ "search_snippets" ] [ query ]
if fetch_messages :
search_method = self . searchForMessages
else :
search_method = self . search... |
def _indent_change ( change , out , options , indent ) :
"""recursive function to print indented change descriptions""" | show_unchanged = getattr ( options , "show_unchanged" , False )
show_ignored = getattr ( options , "show_ignored" , False )
show = False
desc = change . get_description ( )
if change . is_change ( ) :
if change . is_ignored ( options ) :
if show_ignored :
show = True
_indent ( out , ... |
def get_requires ( self , ignored = tuple ( ) ) :
"""The required API , including all external classes , fields , and
methods that this class references""" | if self . _requires is None :
self . _requires = set ( self . _get_requires ( ) )
requires = self . _requires
return [ req for req in requires if not fnmatches ( req , * ignored ) ] |
def parse ( self , data_model , crit ) :
"""Take the relevant pieces of the data model json
and parse into data model and criteria map .
Parameters
data _ model : data model piece of json ( nested dicts )
crit : criteria map piece of json ( nested dicts )
Returns
data _ model : dictionary of DataFrames ... | # data model
tables = pd . DataFrame ( data_model )
data_model = { }
for table_name in tables . columns :
data_model [ table_name ] = pd . DataFrame ( tables [ table_name ] [ 'columns' ] ) . T
# replace np . nan with None
data_model [ table_name ] = data_model [ table_name ] . where ( ( pd . notnull ( data_... |
def _clear_entity_type_registry ( entity , ** kwargs ) :
"""Clear the given database / collection object ' s type registry .""" | codecopts = entity . codec_options . with_options ( type_registry = None )
return entity . with_options ( codec_options = codecopts , ** kwargs ) |
def pdf_to_img ( pdf_file , page_num , pdf_dim = None ) :
"""Converts pdf file into image
: param pdf _ file : path to the pdf file
: param page _ num : page number to convert ( index starting at 1)
: return : wand image object""" | if not pdf_dim :
pdf_dim = get_pdf_dim ( pdf_file )
page_width , page_height = pdf_dim
img = Image ( filename = f"{pdf_file}[{page_num - 1}]" )
img . resize ( page_width , page_height )
return img |
def add_to_class ( self , model_class ) :
"""Replace the ` Field ` attribute with a named ` _ FieldDescriptor ` .
. . note : :
This method is called during construction of the ` Model ` .""" | model_class . _meta . add_field ( self )
setattr ( model_class , self . name , _FieldDescriptor ( self ) ) |
def make_confidence_report ( filepath , train_start = TRAIN_START , train_end = TRAIN_END , test_start = TEST_START , test_end = TEST_END , batch_size = BATCH_SIZE , which_set = WHICH_SET , mc_batch_size = MC_BATCH_SIZE , report_path = REPORT_PATH , base_eps_iter = BASE_EPS_ITER , nb_iter = NB_ITER , save_advx = SAVE_A... | # Set TF random seed to improve reproducibility
tf . set_random_seed ( 1234 )
# Set logging level to see debug information
set_log_level ( logging . INFO )
# Create TF session
sess = tf . Session ( )
if report_path is None :
assert filepath . endswith ( '.joblib' )
report_path = filepath [ : - len ( '.joblib' )... |
def add_features_to_nglview ( view , structure_resnums , chain_id ) :
"""Add select features from the selected SeqProp object to an NGLWidget view object .
Currently parsing for :
* Single residue features ( ie . metal binding sites )
* Disulfide bonds
Args :
view ( NGLWidget ) : NGLWidget view object
s... | # Parse and store chain seq if not already stored
if not structprop . chains . has_id ( chain_id ) :
structprop . parse_structure ( )
if not structprop . chains . has_id ( chain_id ) :
raise ValueError ( 'Chain {} not present in structure {}' . format ( chain_id , structprop . id ) )
if not seqprop . fe... |
def _set_precedence ( self , v , load = False ) :
"""Setter method for precedence , mapped from YANG variable / routing _ system / route _ map / content / precedence ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ precedence is considered as a private
method ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "precedence_value" , precedence . precedence , yang_name = "precedence" , rest_name = "precedence" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys ... |
def blend ( colour1 , colour2 ) :
r"""Takes two : py : class : ` Colour ` s and returns the ' average ' Colour .
Args :
colour1 ( colourettu . Colour ) : a colour
colour2 ( colourettu . Colour ) : a second colour
. . note : :
Uses the formula :
\ \ [ r _ { blended } = \ \ sqrt \ \ frac { r _ 1 ^ 2 + r _... | # raw docstring is needed so that MathJax will render in generated
# documentation
# gamma is the power we ' re going to use to do this conversion
gamma = 2.0
# start by normalizing values
r_1 = colour1 . red ( ) / 255.
g_1 = colour1 . green ( ) / 255.
b_1 = colour1 . blue ( ) / 255.
r_2 = colour2 . red ( ) / 255.
g_2 ... |
def run_fatcat ( structure_path_1 , structure_path_2 , fatcat_sh , outdir = '' , silent = False , print_cmd = False , force_rerun = False ) :
"""Run FATCAT on two PDB files , and return the path of the XML result file .
Args :
structure _ path _ 1 ( str ) : Path to PDB file
structure _ path _ 2 ( str ) : Path... | filename1 = op . splitext ( op . basename ( structure_path_1 ) ) [ 0 ]
filename2 = op . splitext ( op . basename ( structure_path_2 ) ) [ 0 ]
if not op . exists ( outdir ) :
os . mkdir ( outdir )
outfile = op . join ( outdir , filename1 + '__' + filename2 + '.xml' )
# Run FATCAT on the structures , print the XML of... |
def db_parse ( block_id , txid , vtxindex , op , data , senders , inputs , outputs , fee , db_state = None , ** virtualchain_hints ) :
"""( required by virtualchain state engine )
Parse a blockstack operation from a transaction . The transaction fields are as follows :
* ` block _ id ` is the blockchain height ... | # basic sanity checks
if len ( senders ) == 0 :
raise Exception ( "No senders given" )
if not check_tx_sender_types ( senders , block_id ) :
log . warning ( 'Invalid senders for {}' . format ( txid ) )
return None
# this virtualchain instance must give the ' raw _ tx ' hint
assert 'raw_tx' in virtualchain_h... |
def df_weighted_average_grouped ( dataframe , groupe , varlist ) :
'''Agrège les résultats de weighted _ average _ grouped ( ) en une unique dataframe pour la liste de variable ' varlist ' .''' | return DataFrame ( dict ( [ ( var , collapse ( dataframe , groupe , var ) ) for var in varlist ] ) ) |
def build_params ( self , params = { } ) :
"""build a params dictionary with current editId and packageName .
use optional params parameter
to merge additional params into resulting dictionary .""" | z = params . copy ( )
z . update ( { 'editId' : self . edit_id , 'packageName' : self . package_name } )
return z |
def mimeData ( self , items ) :
"""Returns the mime data for dragging for this instance .
: param items | [ < QtGui . QTreeWidgetItem > , . . ]""" | func = self . dataCollector ( )
if func :
return func ( self , items )
data = super ( XTreeWidget , self ) . mimeData ( items )
# return defined custom data
if len ( items ) == 1 :
try :
dragdata = items [ 0 ] . dragData ( )
except AttributeError :
return data
if not data :
data ... |
def configure_db ( self , hostname , database , username , admin = False ) :
"""Configure access to database for username from hostname .""" | self . connect ( password = self . get_mysql_root_password ( ) )
if not self . database_exists ( database ) :
self . create_database ( database )
remote_ip = self . normalize_address ( hostname )
password = self . get_mysql_password ( username )
if not self . grant_exists ( database , username , remote_ip ) :
i... |
def commit_buy ( self , buy_id , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # commit - a - buy""" | return self . api_client . commit_buy ( self . id , buy_id , ** params ) |
def add_signature_headers ( mail , sigs , error_msg ) :
'''Add pseudo headers to the mail indicating whether the signature
verification was successful .
: param mail : : class : ` email . message . Message ` the message to entitle
: param sigs : list of : class : ` gpg . results . Signature `
: param error ... | sig_from = ''
sig_known = True
uid_trusted = False
assert error_msg is None or isinstance ( error_msg , str )
if not sigs :
error_msg = error_msg or u'no signature found'
elif not error_msg :
try :
key = crypto . get_key ( sigs [ 0 ] . fpr )
for uid in key . uids :
if crypto . check_... |
def restrict_args ( func , * args , ** kwargs ) :
'''Restricts the possible arguements to a method to match the func argument .
restrict _ args ( lambda a : a , 1 , 2)''' | callargs = getargspec ( func )
if not callargs . varargs :
args = args [ 0 : len ( callargs . args ) ]
return func ( * args , ** kwargs ) |
def _dedent ( text , tabsize = 8 , skip_first_line = False ) :
"""_ dedent ( text , tabsize = 8 , skip _ first _ line = False ) - > dedented text
" text " is the text to dedent .
" tabsize " is the tab width to use for indent width calculations .
" skip _ first _ line " is a boolean indicating if the first li... | lines = text . splitlines ( 1 )
_dedentlines ( lines , tabsize = tabsize , skip_first_line = skip_first_line )
return '' . join ( lines ) |
def _generate_struct_class_properties ( self , ns , data_type ) :
"""Each field of the struct has a corresponding setter and getter .
The setter validates the value being set .""" | for field in data_type . fields :
field_name = fmt_func ( field . name )
field_name_reserved_check = fmt_func ( field . name , check_reserved = True )
if is_nullable_type ( field . data_type ) :
field_dt = field . data_type . data_type
dt_nullable = True
else :
field_dt = field .... |
def clear_data ( self , request ) :
"""Clear all OAuth related data from the session store .""" | for key in request . session . keys ( ) :
if key . startswith ( constants . SESSION_KEY ) :
del request . session [ key ] |
def parse_bangrc ( ) :
"""Parses ` ` $ HOME / . bangrc ` ` for global settings and deployer credentials . The
` ` . bangrc ` ` file is expected to be a YAML file whose outermost structure is
a key - value map .
Note that even though ` ` . bangrc ` ` is just a YAML file in which a user could
store any top - ... | raw = read_raw_bangrc ( )
return dict ( ( k , raw [ k ] ) for k in raw if k in RC_KEYS ) |
def rogers_huff_r ( gn ) :
"""Estimate the linkage disequilibrium parameter * r * for each pair of
variants using the method of Rogers and Huff ( 2008 ) .
Parameters
gn : array _ like , int8 , shape ( n _ variants , n _ samples )
Diploid genotypes at biallelic variants , coded as the number of
alternate a... | # check inputs
gn = asarray_ndim ( gn , 2 , dtype = 'i1' )
gn = memoryview_safe ( gn )
# compute correlation coefficients
r = gn_pairwise_corrcoef_int8 ( gn )
# convenience for singletons
if r . size == 1 :
r = r [ 0 ]
return r |
def in_venv ( ) :
""": return : True if in running from a virtualenv
Has to detect the case where the python binary is run
directly , so VIRTUAL _ ENV may not be set""" | global _in_venv
if _in_venv is not None :
return _in_venv
if not ( os . path . isfile ( ORIG_PREFIX_TXT ) or os . path . isfile ( PY_VENV_CFG ) ) :
logger . debug ( "in_venv no orig_prefix_txt [%s]" , ORIG_PREFIX_TXT )
logger . debug ( "in_venv no py_venv_cfg [%s]" , PY_VENV_CFG )
# TODO - check this is... |
def del_resource ( self , service_name , resource_name , base_class = None ) :
"""Deletes a resource class for a given service .
Fails silently if no connection is found in the cache .
: param service _ name : The service a given ` ` Resource ` ` talks to . Ex .
` ` sqs ` ` , ` ` sns ` ` , ` ` dynamodb ` ` , ... | # Unlike ` ` get _ resource ` ` , this should be fire & forget .
# We don ' t really care , as long as it ' s not in the cache any longer .
try :
classpath = self . build_classpath ( base_class )
opts = self . services [ service_name ] [ 'resources' ] [ resource_name ]
del opts [ classpath ]
except KeyError... |
def get_roles ( self ) :
"""Return the m2m relations connecting me to creators .
There ' s some publishing - related complexity here . The role relations
( self . creators . through ) connect to draft objects , which then need to
be modified to point to visible ( ) objects .""" | creator_ids = self . get_creators ( ) . values_list ( 'id' , flat = True )
return self . creators . through . objects . filter ( work = self . get_draft ( ) , creator_id__in = creator_ids , ) . select_related ( 'role' ) |
def contractDetails ( self , contract_identifier ) :
"""returns string from contract tuple""" | if isinstance ( contract_identifier , Contract ) :
tickerId = self . tickerId ( contract_identifier )
else :
if str ( contract_identifier ) . isdigit ( ) :
tickerId = contract_identifier
else :
tickerId = self . tickerId ( contract_identifier )
if tickerId in self . contract_details :
re... |
def get_division ( self , row ) :
"""Gets the Division object for the given row of election results .""" | # back out of Alaska county
if ( row [ "level" ] == geography . DivisionLevel . COUNTY and row [ "statename" ] == "Alaska" ) :
print ( "Do not take the Alaska county level result" )
return None
kwargs = { "level__name" : row [ "level" ] }
if row [ "reportingunitname" ] :
name = row [ "reportingunitname" ]
e... |
def str_fraction ( self ) :
"""Returns the fraction with additional whitespace .""" | if self . undefined :
return None
denominator = locale . format ( '%d' , self . denominator , grouping = True )
numerator = self . str_numerator . rjust ( len ( denominator ) )
return '{0}/{1}' . format ( numerator , denominator ) |
def insertionpairs ( args ) :
"""% prog insertionpairs endpoints . bed
Pair up the candidate endpoints . A candidate exision point would contain
both left - end ( LE ) and right - end ( RE ) within a given distance .
( RE ) ( LE )""" | p = OptionParser ( insertionpairs . __doc__ )
p . add_option ( "--extend" , default = 10 , type = "int" , help = "Allow insertion sites to match up within distance" )
p . set_outfile ( )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
bedfile , = args
mergedbedfile... |
def initialize_worker ( self , process_num = None ) :
"""inits producer for a simulation run on a single process""" | self . initial_state . process = process_num
self . random . seed ( hash ( self . seed ) + hash ( process_num ) ) |
def expand_factor_conditions ( s , env ) :
"""If env matches the expanded factor then return value else return ' ' .
Example
> > > s = ' py { 33,34 } : docformatter '
> > > expand _ factor _ conditions ( s , Env ( name = " py34 " , . . . ) )
" docformatter "
> > > expand _ factor _ conditions ( s , Env ( ... | try :
factor , value = re . split ( r'\s*\:\s*' , s )
except ValueError :
return s
if matches_factor_conditions ( factor , env ) :
return value
else :
return '' |
def add_constraints ( self , * args , ** kwargs ) :
"""Add some constraints to the state .
You may pass in any number of symbolic booleans as variadic positional arguments .""" | if len ( args ) > 0 and isinstance ( args [ 0 ] , ( list , tuple ) ) :
raise Exception ( "Tuple or list passed to add_constraints!" )
if o . TRACK_CONSTRAINTS in self . options and len ( args ) > 0 :
if o . SIMPLIFY_CONSTRAINTS in self . options :
constraints = [ self . simplify ( a ) for a in args ]
... |
def check_earthquake_contour_preprocessor ( impact_function ) :
"""Checker for the contour preprocessor .
: param impact _ function : Impact function to check .
: type impact _ function : ImpactFunction
: return : If the preprocessor can run .
: rtype : bool""" | hazard_key = impact_function . hazard . keywords . get ( 'hazard' )
is_earthquake = hazard_key == hazard_earthquake [ 'key' ]
if is_earthquake and is_raster_layer ( impact_function . hazard ) :
return True
else :
return False |
def _number_zero_start_handler ( c , ctx ) :
"""Handles numeric values that start with zero or negative zero . Branches to delegate co - routines according to
_ ZERO _ START _ TABLE .""" | assert c == _ZERO
assert len ( ctx . value ) == 0 or ( len ( ctx . value ) == 1 and ctx . value [ 0 ] == _MINUS )
ctx . set_ion_type ( IonType . INT )
ctx . value . append ( c )
c , _ = yield
if _ends_value ( c ) :
trans = ctx . event_transition ( IonThunkEvent , IonEventType . SCALAR , ctx . ion_type , _parse_deci... |
def get_valid_actions ( name_mapping : Dict [ str , str ] , type_signatures : Dict [ str , Type ] , basic_types : Set [ Type ] , multi_match_mapping : Dict [ Type , List [ Type ] ] = None , valid_starting_types : Set [ Type ] = None , num_nested_lambdas : int = 0 ) -> Dict [ str , List [ str ] ] :
"""Generates all ... | valid_actions : Dict [ str , Set [ str ] ] = defaultdict ( set )
valid_starting_types = valid_starting_types or basic_types
for type_ in valid_starting_types :
valid_actions [ str ( START_TYPE ) ] . add ( _make_production_string ( START_TYPE , type_ ) )
complex_types = set ( )
for name , alias in name_mapping . ite... |
def saveh5 ( self , h5file , qpi_slice = None , series_slice = None , time_interval = None , count = None , max_count = None ) :
"""Save the data set as an hdf5 file ( qpimage . QPSeries format )
Parameters
h5file : str , pathlib . Path , or h5py . Group
Where to store the series data
qpi _ slice : tuple of... | # set up slice to export
if series_slice is None :
sl = range ( len ( self ) )
else :
sl = range ( series_slice . start , series_slice . stop )
# set up time interval
if time_interval is None :
ta = - np . inf
tb = np . inf
else :
ta , tb = time_interval
# set max _ count according to slice
if max_c... |
def segment_midpoints_by_vertices ( self , vertices ) :
"""Add midpoints to any segment connected to the vertices in the
list / array provided .""" | segments = set ( )
for vertex in vertices :
neighbours = self . identify_vertex_neighbours ( vertex )
segments . update ( min ( tuple ( ( vertex , n1 ) ) , tuple ( ( n1 , vertex ) ) ) for n1 in neighbours )
segs = np . array ( list ( segments ) )
new_midpoint_lonlats = self . segment_midpoints ( segments = segs... |
def sequences_from_fasta ( path ) :
"""Extract multiple sequences from a FASTA file .""" | from Bio import SeqIO
return { x . description : x . seq for x in SeqIO . parse ( path , 'fasta' ) } |
def get_template ( self , template_id ) :
"""Get the template for a given template id .
: param template _ id : id of the template , str
: return :""" | template = self . contract_concise . getTemplate ( template_id )
if template and len ( template ) == 4 :
return AgreementTemplate ( * template )
return None |
def vb_get_network_addresses ( machine_name = None , machine = None , wait_for_pattern = None ) :
'''TODO distinguish between private and public addresses
A valid machine _ name or a machine is needed to make this work !
Guest prerequisite : GuestAddition
Thanks to Shrikant Havale for the StackOverflow answer... | if machine_name :
machine = vb_get_box ( ) . findMachine ( machine_name )
ip_addresses = [ ]
log . debug ( "checking for power on:" )
if machine . state == _virtualboxManager . constants . MachineState_Running :
log . debug ( "got power on:" )
# wait on an arbitrary named property
# for instance use a d... |
def parse ( self , arguments = None ) :
"""Parse the shared [ i ] did arguments""" | arguments = self . arguments or arguments
# FIXME : prep / normalize arguments in _ _ init _ _
# Split arguments if given as string and run the parser
if isinstance ( arguments , basestring ) :
arguments = utils . split ( arguments )
# run the wrapped argparser command to gather user set arg values
# FROM : https :... |
def resolve ( self , key ) :
"""Looks up a variable like ` _ _ getitem _ _ ` or ` get ` but returns an
: class : ` Undefined ` object with the name of the name looked up .""" | if key in self . vars :
return self . vars [ key ]
if key in self . parent :
return self . parent [ key ]
return self . environment . undefined ( name = key ) |
def uri_to_iri ( uri , charset = 'utf-8' , errors = 'replace' ) :
r"""Converts a URI in a given charset to a IRI .
Examples for URI versus IRI :
> > > uri _ to _ iri ( b ' http : / / xn - - n3h . net / ' )
u ' http : / / \ u2603 . net / '
> > > uri _ to _ iri ( b ' http : / / % C3 % BCser : p % C3 % A4sswor... | if isinstance ( uri , tuple ) :
uri = url_unparse ( uri )
uri = url_parse ( to_unicode ( uri , charset ) )
path = url_unquote ( uri . path , charset , errors , '/;?' )
query = url_unquote ( uri . query , charset , errors , ';/?:@&=+,$' )
fragment = url_unquote ( uri . fragment , charset , errors , ';/?:@&=+,$' )
re... |
def set_xlim_cb ( self , redraw = True ) :
"""Set plot limit based on user values .""" | try :
xmin = float ( self . w . x_lo . get_text ( ) )
except Exception :
set_min = True
else :
set_min = False
try :
xmax = float ( self . w . x_hi . get_text ( ) )
except Exception :
set_max = True
else :
set_max = False
if set_min or set_max :
self . tab_plot . draw ( )
self . set_xlim... |
def show_low_sls ( mods , test = None , queue = False , ** kwargs ) :
'''Display the low data from a specific sls . The default environment is
` ` base ` ` , use ` ` saltenv ` ` to specify a different environment .
saltenv
Specify a salt fileserver environment to be used when applying states
pillar
Custom... | if 'env' in kwargs : # " env " is not supported ; Use " saltenv " .
kwargs . pop ( 'env' )
conflict = _check_queue ( queue , kwargs )
if conflict is not None :
return conflict
orig_test = __opts__ . get ( 'test' , None )
opts = salt . utils . state . get_sls_opts ( __opts__ , ** kwargs )
opts [ 'test' ] = _get_... |
def create_authz_decision_query ( self , destination , action , evidence = None , resource = None , subject = None , message_id = 0 , consent = None , extensions = None , sign = None , sign_alg = None , digest_alg = None , ** kwargs ) :
"""Creates an authz decision query .
: param destination : The IdP endpoint
... | return self . _message ( AuthzDecisionQuery , destination , message_id , consent , extensions , sign , action = action , evidence = evidence , resource = resource , subject = subject , sign_alg = sign_alg , digest_alg = digest_alg , ** kwargs ) |
def _fetch_partition_info ( self , topic_id , partition_id ) :
"""Fetch partition info for given topic - partition .""" | info_path = "/brokers/topics/{topic_id}/partitions/{p_id}"
try :
_ , partition_info = self . get ( info_path . format ( topic_id = topic_id , p_id = partition_id ) , )
return partition_info
except NoNodeError :
return { } |
def data ( self , column , role ) :
"""Return the data for the specified column and role
The column addresses one attribute of the data .
: param column : the data column
: type column : int
: param role : the data role
: type role : QtCore . Qt . ItemDataRole
: returns : data depending on the role
: ... | return self . columns [ column ] ( self . _atype , role ) |
def potential_purviews ( self , direction , mechanism , purviews = False ) :
"""Return all purviews that could belong to the | MIC | / | MIE | .
Filters out trivially - reducible purviews .
Args :
direction ( str ) : Either | CAUSE | or | EFFECT | .
mechanism ( tuple [ int ] ) : The mechanism of interest . ... | system = self . system [ direction ]
return [ purview for purview in system . potential_purviews ( direction , mechanism , purviews ) if set ( purview ) . issubset ( self . purview_indices ( direction ) ) ] |
def execute ( self ) :
"""Execute a system command .""" | if self . _decode_output : # Capture and decode system output
with Popen ( self . command , shell = True , stdout = PIPE ) as process :
self . _output = [ i . decode ( "utf-8" ) . strip ( ) for i in process . stdout ]
self . _success = True
else : # Execute without capturing output
os . system (... |
def gen_thin ( cachedir , extra_mods = '' , overwrite = False , so_mods = '' , python2_bin = 'python2' , python3_bin = 'python3' , absonly = True , compress = 'gzip' , extended_cfg = None ) :
'''Generate the salt - thin tarball and print the location of the tarball
Optional additional mods to include ( e . g . ma... | if sys . version_info < ( 2 , 6 ) :
raise salt . exceptions . SaltSystemExit ( 'The minimum required python version to run salt-ssh is "2.6".' )
if compress not in [ 'gzip' , 'zip' ] :
log . warning ( 'Unknown compression type: "%s". Falling back to "gzip" compression.' , compress )
compress = 'gzip'
thindi... |
def chromosomes_from_fai ( genome_fai ) :
"""Read a fasta index ( fai ) file and parse the input chromosomes .
: param str genome _ fai : Path to the fai file .
: return : list of input chromosomes
: rtype : list [ str ]""" | chromosomes = [ ]
with open ( genome_fai ) as fai_file :
for line in fai_file :
line = line . strip ( ) . split ( )
chromosomes . append ( line [ 0 ] )
return chromosomes |
def on_update ( self , value , * args , ** kwargs ) :
"""Inform the parent of progress .
: param value : The value of this subprogresscallback
: param args : Extra positional arguments
: param kwargs : Extra keyword arguments""" | parent_value = self . _parent_min
if self . _max != self . _min :
sub_progress = ( value - self . _min ) / ( self . _max - self . _min )
parent_value = self . _parent_min + sub_progress * ( self . _parent_max - self . _parent_min )
self . _parent . update ( parent_value , * args , ** kwargs ) |
def build_columns ( self , X , verbose = False ) :
"""construct the model matrix columns for the term
Parameters
X : array - like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
scipy sparse array with n rows""" | return sp . sparse . csc_matrix ( X [ : , self . feature ] [ : , np . newaxis ] ) |
def decode_params ( params ) :
"""Decode parameters list according to RFC 2231.
params is a sequence of 2 - tuples containing ( param name , string value ) .""" | # Copy params so we don ' t mess with the original
params = params [ : ]
new_params = [ ]
# Map parameter ' s name to a list of continuations . The values are a
# 3 - tuple of the continuation number , the string value , and a flag
# specifying whether a particular segment is % - encoded .
rfc2231_params = { }
name , v... |
def connection_factory ( self , endpoint , * args , ** kwargs ) :
"""Called to create a new connection with proper configuration .
Intended for internal use only .""" | kwargs = self . _make_connection_kwargs ( endpoint , kwargs )
return self . connection_class . factory ( endpoint , self . connect_timeout , * args , ** kwargs ) |
def find ( self , instance_ids = None , filters = None ) :
"""Flatten list of reservations to a list of instances .
: param instance _ ids : A list of instance ids to filter by
: type instance _ ids : list
: param filters : A dict of Filter . N values defined in http : / / goo . gl / jYNej9
: type filters :... | instances = [ ]
reservations = self . retry_on_ec2_error ( self . ec2 . get_all_instances , instance_ids = instance_ids , filters = filters )
for reservation in reservations :
instances . extend ( reservation . instances )
return instances |
def do_help ( self , arg ) :
"""List available commands with " help " or detailed help with " help cmd " .""" | if arg : # XXX check arg syntax
try :
func = getattr ( self , 'help_' + arg )
except AttributeError :
try :
doc = getattr ( self , 'do_' + arg ) . __doc__
if doc :
self . stdout . write ( "%s\n" % str ( doc ) )
return
except Attribu... |
def set_codes ( self , codes , reject = False ) :
"""Set the accepted or rejected codes codes list .
: param codes : A list of the response codes .
: param reject : If True , the listed codes will be rejected , and
the conversion will format as " - " ; if False ,
only the listed codes will be accepted , and... | self . codes = set ( codes )
self . reject = reject |
def _flush_bits_to_stream ( self ) :
"""Flush the bits to the stream . This is used when
a few bits have been read and ` ` self . _ bits ` ` contains unconsumed /
flushed bits when data is to be written to the stream""" | if len ( self . _bits ) == 0 :
return 0
bits = list ( self . _bits )
diff = 8 - ( len ( bits ) % 8 )
padding = [ 0 ] * diff
bits = bits + padding
self . _stream . write ( bits_to_bytes ( bits ) )
self . _bits . clear ( ) |
def delete_if_exists ( self , ** kwargs ) :
"""Deletes an object if it exists in database according to given query
parameters and returns True otherwise does nothing and returns False .
Args :
* * kwargs : query parameters
Returns ( bool ) : True or False""" | try :
self . get ( ** kwargs ) . blocking_delete ( )
return True
except ObjectDoesNotExist :
return False |
def outputdata ( self , data ) :
"""Send output with fixed length data""" | if not isinstance ( data , bytes ) :
data = str ( data ) . encode ( self . encoding )
self . output ( MemoryStream ( data ) ) |
def get_spot ( self , feature = None , ** kwargs ) :
"""Shortcut to : meth : ` get _ feature ` but with kind = ' spot '""" | kwargs . setdefault ( 'kind' , 'spot' )
return self . get_feature ( feature , ** kwargs ) |
def wait_for_ready_state_complete ( driver , timeout = settings . EXTREME_TIMEOUT ) :
"""The DOM ( Document Object Model ) has a property called " readyState " .
When the value of this becomes " complete " , page resources are considered
fully loaded ( although AJAX and other loads might still be happening ) . ... | start_ms = time . time ( ) * 1000.0
stop_ms = start_ms + ( timeout * 1000.0 )
for x in range ( int ( timeout * 10 ) ) :
try :
ready_state = driver . execute_script ( "return document.readyState" )
except WebDriverException : # Bug fix for : [ Permission denied to access property " document " ]
t... |
def _g_func ( self ) :
"""Eq . 20 in Peters and Mathews 1963.""" | return ( self . n ** 4. / 32. * ( ( jv ( self . n - 2. , self . n * self . e_vals ) - 2. * self . e_vals * jv ( self . n - 1. , self . n * self . e_vals ) + 2. / self . n * jv ( self . n , self . n * self . e_vals ) + 2. * self . e_vals * jv ( self . n + 1. , self . n * self . e_vals ) - jv ( self . n + 2. , self . n *... |
def _tp_cache ( func ) :
"""Internal wrapper caching _ _ getitem _ _ of generic types with a fallback to
original function for non - hashable arguments .""" | cached = functools . lru_cache ( ) ( func )
_cleanups . append ( cached . cache_clear )
@ functools . wraps ( func )
def inner ( * args , ** kwds ) :
try :
return cached ( * args , ** kwds )
except TypeError :
pass
# All real errors ( not unhashable args ) are raised below .
return f... |
def _get_default_annual_spacing ( nyears ) :
"""Returns a default spacing between consecutive ticks for annual data .""" | if nyears < 11 :
( min_spacing , maj_spacing ) = ( 1 , 1 )
elif nyears < 20 :
( min_spacing , maj_spacing ) = ( 1 , 2 )
elif nyears < 50 :
( min_spacing , maj_spacing ) = ( 1 , 5 )
elif nyears < 100 :
( min_spacing , maj_spacing ) = ( 5 , 10 )
elif nyears < 200 :
( min_spacing , maj_spacing ) = ( 5 ... |
def get_constructor ( self ) :
""": returns : A function that constructs this gate on variable qubit indices . E . g .
` mygate . get _ constructor ( ) ( 1 ) applies the gate to qubit 1 . `""" | if self . parameters :
return lambda * params : lambda * qubits : Gate ( name = self . name , params = list ( params ) , qubits = list ( map ( unpack_qubit , qubits ) ) )
else :
return lambda * qubits : Gate ( name = self . name , params = [ ] , qubits = list ( map ( unpack_qubit , qubits ) ) ) |
def hotkey ( * args , ** kwargs ) :
"""Performs key down presses on the arguments passed in order , then performs
key releases in reverse order .
The effect is that calling hotkey ( ' ctrl ' , ' shift ' , ' c ' ) would perform a
" Ctrl - Shift - C " hotkey / keyboard shortcut press .
Args :
key ( s ) ( st... | interval = float ( kwargs . get ( 'interval' , 0.0 ) )
_failSafeCheck ( )
for c in args :
if len ( c ) > 1 :
c = c . lower ( )
platformModule . _keyDown ( c )
time . sleep ( interval )
for c in reversed ( args ) :
if len ( c ) > 1 :
c = c . lower ( )
platformModule . _keyUp ( c )
... |
def update ( context , id , etag , name , country , parent_id , active , external ) :
"""update ( context , id , etag , name , country , parent _ id , active , external )
Update a team .
> > > dcictl team - update [ OPTIONS ]
: param string id : ID of the team to update [ required ]
: param string etag : En... | result = team . update ( context , id = id , etag = etag , name = name , state = utils . active_string ( active ) , country = country , parent_id = parent_id , external = external )
utils . format_output ( result , context . format ) |
def request_xml ( url , auth = None ) :
'''Returns an etree . XMLRoot object loaded from the url
: param str url : URL for the resource to load as an XML''' | try :
r = requests . get ( url , auth = auth , verify = False )
return r . text . encode ( 'utf-8' )
except BaseException :
logger . error ( "Skipping %s (error parsing the XML)" % url )
return |
def kill_cursors ( cursor_ids ) :
"""Get a * * killCursors * * message .""" | data = _ZERO_32
data += struct . pack ( "<i" , len ( cursor_ids ) )
for cursor_id in cursor_ids :
data += struct . pack ( "<q" , cursor_id )
return __pack_message ( 2007 , data ) |
def remove_hop_by_hop_headers ( headers ) :
"""Remove all HTTP / 1.1 " Hop - by - Hop " headers from a list or
: class : ` Headers ` object . This operation works in - place .
. . versionadded : : 0.5
: param headers : a list or : class : ` Headers ` object .""" | headers [ : ] = [ ( key , value ) for key , value in headers if not is_hop_by_hop_header ( key ) ] |
def close_stream_on_error ( func ) :
'''Decorator to close stream on error .''' | @ asyncio . coroutine
@ functools . wraps ( func )
def wrapper ( self , * args , ** kwargs ) :
with wpull . util . close_on_error ( self . close ) :
return ( yield from func ( self , * args , ** kwargs ) )
return wrapper |
def find_string_ids ( self , substring , suffix_tree_id , limit = None ) :
"""Returns a set of IDs for strings that contain the given substring .""" | # Find an edge for the substring .
edge , ln = self . find_substring_edge ( substring = substring , suffix_tree_id = suffix_tree_id )
# If there isn ' t an edge , return an empty set .
if edge is None :
return set ( )
# Get all the string IDs beneath the edge ' s destination node .
string_ids = get_string_ids ( nod... |
def plot_di_mean ( dec , inc , a95 , color = 'k' , marker = 'o' , markersize = 20 , label = '' , legend = 'no' ) :
"""Plot a mean direction ( declination , inclination ) with alpha _ 95 ellipse on
an equal area plot .
Before this function is called , a plot needs to be initialized with code
that looks somethi... | DI_dimap = pmag . dimap ( dec , inc )
if inc < 0 :
plt . scatter ( DI_dimap [ 0 ] , DI_dimap [ 1 ] , edgecolors = color , facecolors = 'white' , marker = marker , s = markersize , label = label )
if inc >= 0 :
plt . scatter ( DI_dimap [ 0 ] , DI_dimap [ 1 ] , edgecolors = color , facecolors = color , marker = m... |
def collection_location ( obj ) :
"""Get the URL for the collection of objects like ` ` obj ` ` .
: param obj : Either a type representing a Kubernetes object kind or an
instance of such a type .
: return tuple [ unicode ] : Some path segments to stick on to a base URL to
construct the location of the colle... | # TODO kind is not part of IObjectLoader and we should really be loading
# apiVersion off of this object too .
kind = obj . kind
apiVersion = obj . apiVersion
prefix = version_to_segments [ apiVersion ]
collection = kind . lower ( ) + u"s"
if IObject . providedBy ( obj ) : # Actual objects * could * have a namespace . ... |
def _write_dihedral_information ( xml_file , structure , ref_energy ) :
"""Write dihedrals in the system .
Parameters
xml _ file : file object
The file object of the hoomdxml file being written
structure : parmed . Structure
Parmed structure object
ref _ energy : float , default = 1.0
Reference energy... | unique_dihedral_types = set ( )
xml_file . write ( '<dihedral>\n' )
for dihedral in structure . rb_torsions :
t1 , t2 = dihedral . atom1 . type , dihedral . atom2 . type , t3 , t4 = dihedral . atom3 . type , dihedral . atom4 . type
if [ t2 , t3 ] == sorted ( [ t2 , t3 ] ) :
types_in_dihedral = '-' . joi... |
def get_unique_values ( dictionary_input ) :
"""Function to retrieve unique values from input dictionary values .
> > > get _ unique _ values ( { ' msm ' : [ 5 , 6 , 7 , 8 ] , ' is ' : [ 10 , 11 , 7 , 5 ] , ' best ' : [ 6 , 12 , 10 , 8 ] , ' for ' : [ 1 , 2 , 5 ] } )
[1 , 2 , 5 , 6 , 7 , 8 , 10 , 11 , 12]
> >... | unique_output = list ( sorted ( set ( value for sublist in dictionary_input . values ( ) for value in sublist ) ) )
return unique_output |
def _safebuiltins ( ) :
"""Construct a safe builtin environment without I / O functions .
: rtype : dict""" | result = { }
objectnames = [ objectname for objectname in dir ( builtins ) if objectname not in BUILTIN_IO_PROPS ]
for objectname in objectnames :
result [ objectname ] = getattr ( builtins , objectname )
return result |
def factor ( self , data : [ 'SASdata' , str ] = None , by : str = None , cls : [ str , list ] = None , freq : str = None , paired : str = None , var : str = None , weight : str = None , procopts : str = None , stmtpassthrough : str = None , ** kwargs : dict ) -> 'SASresults' :
"""Python method to call the FACTOR p... | |
def _delete_forever_values ( self , forever_key ) :
"""Delete all of the keys that have been stored forever .
: type forever _ key : str""" | forever = self . _store . connection ( ) . lrange ( forever_key , 0 , - 1 )
if len ( forever ) > 0 :
self . _store . connection ( ) . delete ( * forever ) |
def observe ( self , body ) :
"""Compute the ` Astrometric ` position of a body from this location .
To compute the body ' s astrometric position , it is first asked
for its position at the time ` t ` of this position itself . The
distance to the body is then divided by the speed of light to
find how long i... | p , v , t , light_time = body . _observe_from_bcrs ( self )
astrometric = Astrometric ( p , v , t , observer_data = self . observer_data )
astrometric . light_time = light_time
return astrometric |
def plotSolidAngleCMD ( self ) :
"""Solid angle within the mask as a function of color and magnitude .""" | msg = "'%s.plotSolidAngleCMD': ADW 2018-05-05" % self . __class__ . __name__
DeprecationWarning ( msg )
import ugali . utils . plotting
ugali . utils . plotting . twoDimensionalHistogram ( 'mask' , 'color' , 'magnitude' , self . solid_angle_cmd , self . roi . bins_color , self . roi . bins_mag , lim_x = [ self . roi . ... |
def return_periods ( eff_time , num_losses ) :
""": param eff _ time : ses _ per _ logic _ tree _ path * investigation _ time
: param num _ losses : used to determine the minimum period
: returns : an array of 32 bit periods
Here are a few examples :
> > > return _ periods ( 1 , 1)
Traceback ( most recent... | assert eff_time >= 2 , 'eff_time too small: %s' % eff_time
assert num_losses >= 2 , 'num_losses too small: %s' % num_losses
min_time = eff_time / num_losses
period = 1
periods = [ ]
loop = True
while loop :
for val in [ 1 , 2 , 5 ] :
time = period * val
if time >= min_time :
if time > ef... |
def separable_series ( h , N = 1 ) :
"""finds the first N rank 1 tensors such that their sum approximates
the tensor h ( 2d or 3d ) best
returns ( e . g . for 3d case ) res = ( hx , hy , hz ) [ i ]
s . t .
h \a pprox sum _ i einsum ( " i , j , k " , res [ i , 0 ] , res [ i , 1 ] , res [ i , 2 ] )
Paramete... | if h . ndim == 2 :
return _separable_series2 ( h , N )
elif h . ndim == 3 :
return _separable_series3 ( h , N )
else :
raise ValueError ( "unsupported array dimension: %s (only 2d or 3d) " % h . ndim ) |
def save ( self ) :
"""save or update endpoint to Ariane server
: return :""" | LOGGER . debug ( "Endpoint.save" )
if self . parent_node is not None :
if self . parent_node . id is None :
self . parent_node . save ( )
self . parent_node_id = self . parent_node . id
post_payload = { }
consolidated_twin_endpoints_id = [ ]
consolidated_properties = { }
consolidated_endpoint_properties... |
def _sim ( self , xg , ancs1 , ancs2 , pfx1 , pfx2 ) :
"""Compare two lineages""" | xancs1 = set ( )
for a in ancs1 :
if a in xg : # TODO : restrict this to neighbors in single ontology
for n in xg . neighbors ( a ) :
pfx = self . _id_to_ontology ( n )
if pfx == pfx2 :
xancs1 . add ( n )
logging . debug ( 'SIM={}/{} ## {}' . format ( len ( xancs1 . i... |
def load_projections ( folder , indices = None ) :
"""Load geometry and data stored in Mayo format from folder .
Parameters
folder : str
Path to the folder where the Mayo DICOM files are stored .
indices : optional
Indices of the projections to load .
Accepts advanced indexing such as slice or list of i... | datasets , data_array = _read_projections ( folder , indices )
# Get the angles
angles = [ d . DetectorFocalCenterAngularPosition for d in datasets ]
angles = - np . unwrap ( angles ) - np . pi
# different defintion of angles
# Set minimum and maximum corners
shape = np . array ( [ datasets [ 0 ] . NumberofDetectorColu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.