signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def cmd ( send , _ , args ) :
"""Returns a listing of the current channels .
Syntax : { command }""" | with args [ 'handler' ] . data_lock :
channels = ", " . join ( sorted ( args [ 'handler' ] . channels ) )
send ( channels ) |
def get_image_set ( self ) :
"""Obtain existing ImageSet if ` pk ` is specified , otherwise
create a new ImageSet for the user .""" | image_set_pk = self . kwargs . get ( "pk" , None )
if image_set_pk is None :
return self . request . user . image_sets . create ( )
return get_object_or_404 ( self . get_queryset ( ) , pk = image_set_pk ) |
def owned_objects ( self ) :
"""List of gc - tracked objects owned by this ObjectGraph instance .""" | return ( [ self , self . __dict__ , self . _head , self . _tail , self . _out_edges , self . _out_edges . _keys , self . _out_edges . _values , self . _in_edges , self . _in_edges . _keys , self . _in_edges . _values , self . _vertices , self . _vertices . _elements , self . _edges , ] + list ( six . itervalues ( self ... |
def get_comment_create_data ( self ) :
"""Returns the dict of data to be used to create a comment . Subclasses in
custom comment apps that override get _ comment _ model can override this
method to add extra fields onto a custom comment model .""" | user_model = get_user_model ( )
return dict ( content_type = ContentType . objects . get_for_model ( self . target_object ) , object_pk = force_text ( self . target_object . _get_pk_val ( ) ) , text = self . cleaned_data [ "text" ] , user = user_model . objects . latest ( 'id' ) , post_date = timezone . now ( ) , site_... |
def parse_command_line ( argv ) :
"""Parse command line argument . See - h option .
Arguments :
argv : arguments on the command line must include caller file name .""" | import textwrap
example = textwrap . dedent ( """
Examples:
# Simple string substitution (-e). Will show a diff. No changes applied.
{0} -e "re.sub('failIf', 'assertFalse', line)" *.py
# File level modifications (-f). Overwrites the files in place (-w).
{0} -w -f fixer:fixit *.py
# Will change... |
def show_notification ( cls , channel_id , * args , ** kwargs ) :
"""Create and show a Notification . See ` Notification . Builder . update `
for a list of accepted parameters .""" | app = AndroidApplication . instance ( )
builder = Notification . Builder ( app , channel_id )
builder . update ( * args , ** kwargs )
return builder . show ( ) |
def BackAssign ( cls , other_entity_klass , this_entity_backpopulate_field , other_entity_backpopulate_field , is_many_to_one = False ) :
"""Assign defined one side mapping relationship to other side .
For example , each employee belongs to one department , then one department
includes many employees . If you d... | data = dict ( )
for _ , other_klass in other_entity_klass . Subclasses ( ) :
other_field_value = getattr ( other_klass , this_entity_backpopulate_field )
if isinstance ( other_field_value , ( tuple , list ) ) :
for self_klass in other_field_value :
self_key = self_klass . __name__
... |
def stelab ( pobj , vobs ) :
"""Correct the apparent position of an object for stellar
aberration .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / stelab _ c . html
: param pobj : Position of an object with respect to the observer .
: type pobj : 3 - Element Array of floats ... | pobj = stypes . toDoubleVector ( pobj )
vobs = stypes . toDoubleVector ( vobs )
appobj = stypes . emptyDoubleVector ( 3 )
libspice . stelab_c ( pobj , vobs , appobj )
return stypes . cVectorToPython ( appobj ) |
def network_traffic_ports ( instance ) :
"""Ensure network - traffic objects contain both src _ port and dst _ port .""" | for key , obj in instance [ 'objects' ] . items ( ) :
if ( 'type' in obj and obj [ 'type' ] == 'network-traffic' and ( 'src_port' not in obj or 'dst_port' not in obj ) ) :
yield JSONError ( "The Network Traffic object '%s' should contain " "both the 'src_port' and 'dst_port' properties." % key , instance [ ... |
def updateImage ( self , imgdata , xaxis = None , yaxis = None ) :
"""Updates the Widget image directly .
: type imgdata : numpy . ndarray , see : meth : ` pyqtgraph : pyqtgraph . ImageItem . setImage `
: param xaxis : x - axis values , length should match dimension 1 of imgdata
: param yaxis : y - axis value... | imgdata = imgdata . T
self . img . setImage ( imgdata )
if xaxis is not None and yaxis is not None :
xscale = 1.0 / ( imgdata . shape [ 0 ] / xaxis [ - 1 ] )
yscale = 1.0 / ( imgdata . shape [ 1 ] / yaxis [ - 1 ] )
self . resetScale ( )
self . img . scale ( xscale , yscale )
self . imgScale = ( xsca... |
def header ( fname , sep = "\t" ) :
"""just grab the header from a given file""" | fh = iter ( nopen ( fname ) )
h = tokens ( next ( fh ) , sep )
h [ 0 ] = h [ 0 ] . lstrip ( "#" )
return h |
def get ( self , session , fields = [ ] ) :
'''taobao . postages . get 获取卖家的运费模板
获得当前会话用户的所有邮费模板''' | request = TOPRequest ( 'taobao.postages.get' )
if not fields :
postage = Postage ( )
fields = postage . fields
request [ 'fields' ] = fields
self . create ( self . execute ( request , session ) )
return self . postages |
def usufyToXlsxExport ( d , fPath ) :
"""Workaround to export to a . xlsx file .
Args :
d : Data to export .
fPath : File path for the output file .""" | from pyexcel_xlsx import get_data
try : # oldData = get _ data ( fPath )
# A change in the API now returns only an array of arrays if there is only one sheet .
oldData = { "OSRFramework" : get_data ( fPath ) }
except : # No information has been recovered
oldData = { "OSRFramework" : [ ] }
# Generating the new t... |
def asizesof ( * objs , ** opts ) :
'''Return a tuple containing the size in bytes of all objects
passed as positional argments using the following options .
* align = 8 * - - size alignment
* clip = 80 * - - clip ` ` repr ( ) ` ` strings
* code = False * - - incl . ( byte ) code size
* derive = False * -... | if 'all' in opts :
raise KeyError ( 'invalid option: %s=%r' % ( 'all' , opts [ 'all' ] ) )
if objs : # size given objects
_asizer . reset ( ** opts )
t = _asizer . asizesof ( * objs )
_asizer . print_stats ( objs , opts = opts , sizes = t )
# show opts as _ kwdstr
_asizer . _clear ( )
else :
... |
def execute ( self , input_data ) :
'''Execute the URL worker''' | string_output = input_data [ 'strings' ] [ 'string_list' ]
flatten = ' ' . join ( string_output )
urls = self . url_match . findall ( flatten )
return { 'url_list' : urls } |
def post ( self , request , question_level , question_number , format = None ) :
"""Use this Function to submit Comment .""" | user = User . objects . get ( username = request . user . username )
question = Question . objects . filter ( question_level = question_level ) . filter ( question_number = question_number )
if int ( user . profile . user_access_level ) < int ( question_level ) :
content = { 'user_nick' : profile . user_nick , 'ple... |
def or_ ( self , first_qe , * qes ) :
'''Add a $ not expression to the query , negating the query expressions
given . The ` ` | operator ` ` on query expressions does the same thing
* * Examples * * : ` ` query . or _ ( SomeDocClass . age = = 18 , SomeDocClass . age = = 17 ) ` ` becomes ` ` { ' $ or ' : [ { ' a... | res = first_qe
for qe in qes :
res = ( res | qe )
self . filter ( res )
return self |
def data_from_cli ( opts ) :
"""Loads the data needed for a model from the given
command - line options . Gates specifed on the command line are also applied .
Parameters
opts : ArgumentParser parsed args
Argument options parsed from a command line string ( the sort of thing
returned by ` parser . parse _... | # get gates to apply
gates = gates_from_cli ( opts )
psd_gates = psd_gates_from_cli ( opts )
# get strain time series
instruments = opts . instruments if opts . instruments is not None else [ ]
strain_dict = strain_from_cli_multi_ifos ( opts , instruments , precision = "double" )
# apply gates if not waiting to overwhi... |
def transfer_to ( self , cloudpath , bbox , block_size = None , compress = True ) :
"""Transfer files from one storage location to another , bypassing
volume painting . This enables using a single CloudVolume instance
to transfer big volumes . In some cases , gsutil or aws s3 cli tools
may be more appropriate... | if type ( bbox ) is Bbox :
requested_bbox = bbox
else :
( requested_bbox , _ , _ ) = self . __interpret_slices ( bbox )
realized_bbox = self . __realized_bbox ( requested_bbox )
if requested_bbox != realized_bbox :
raise exceptions . AlignmentError ( "Unable to transfer non-chunk aligned bounding boxes. Req... |
def vm_config ( name , main , provider , profile , overrides ) :
'''Create vm config .
: param str name : The name of the vm
: param dict main : The main cloud config
: param dict provider : The provider config
: param dict profile : The profile config
: param dict overrides : The vm ' s config overrides'... | vm = main . copy ( )
vm = salt . utils . dictupdate . update ( vm , provider )
vm = salt . utils . dictupdate . update ( vm , profile )
vm . update ( overrides )
vm [ 'name' ] = name
return vm |
def gridLog ( ** kw ) :
"""Send GLRecord , Distributed Logging Utilities
If the scheme is passed as a keyword parameter
the value is expected to be a callable function
that takes 2 parameters : url , outputStr
GRIDLOG _ ON - - turn grid logging on
GRIDLOG _ DEST - - provide URL destination""" | import os
if not bool ( int ( os . environ . get ( 'GRIDLOG_ON' , 0 ) ) ) :
return
url = os . environ . get ( 'GRIDLOG_DEST' )
if url is None :
return
# # NOTE : urlparse problem w / customized schemes
try :
scheme = url [ : url . find ( '://' ) ]
send = GLRegistry [ scheme ]
send ( url , str ( GLRe... |
async def command ( dev , service , method , parameters ) :
"""Run a raw command .""" | params = None
if parameters is not None :
params = ast . literal_eval ( parameters )
click . echo ( "Calling %s.%s with params %s" % ( service , method , params ) )
res = await dev . raw_command ( service , method , params )
click . echo ( res ) |
def run ( self , * args , ** kwargs ) :
"""This runs in a greenlet""" | return_value = self . coro ( * args , ** kwargs )
# i don ' t like this but greenlets are so dodgy i have no other choice
raise StopIteration ( return_value ) |
def _extract_word ( self , source , position ) :
"""Extracts the word that falls at or around a specific position
: param source :
The template source as a unicode string
: param position :
The position where the word falls
: return :
The word""" | boundry = re . search ( '{{|{|\s|$' , source [ : position ] [ : : - 1 ] )
start_offset = boundry . end ( ) if boundry . group ( 0 ) . startswith ( '{' ) else boundry . start ( )
boundry = re . search ( '}}|}|\s|$' , source [ position : ] )
end_offset = boundry . end ( ) if boundry . group ( 0 ) . startswith ( '}' ) els... |
def side_chain_centres ( assembly , masses = False ) :
"""PseudoGroup containing side _ chain centres of each Residue in each Polypeptide in Assembly .
Notes
Each PseudoAtom is a side - chain centre .
There is one PseudoMonomer per chain in ampal ( each containing len ( chain ) PseudoAtoms ) .
The PseudoGro... | if masses :
elts = set ( [ x . element for x in assembly . get_atoms ( ) ] )
masses_dict = { e : element_data [ e ] [ 'atomic mass' ] for e in elts }
pseudo_monomers = [ ]
for chain in assembly :
if isinstance ( chain , Polypeptide ) :
centres = OrderedDict ( )
for r in chain . get_monomers ... |
def set_io_qubits ( qubit_count ) :
"""Add the specified number of input and output qubits .""" | input_qubits = [ cirq . GridQubit ( i , 0 ) for i in range ( qubit_count ) ]
output_qubit = cirq . GridQubit ( qubit_count , 0 )
return ( input_qubits , output_qubit ) |
def adapt_item ( item , package , filename = None ) :
"""Adapts ` ` . epub . Item ` ` to a ` ` DocumentItem ` ` .""" | if item . media_type == 'application/xhtml+xml' :
try :
html = etree . parse ( item . data )
except Exception as exc :
logger . error ( "failed parsing {}" . format ( item . name ) )
raise
metadata = DocumentPointerMetadataParser ( html , raise_value_error = False ) ( )
item . da... |
def poify ( self , model ) :
"""turn a django model into a po file .""" | if not hasattr ( model , 'localized_fields' ) :
return None
# create po stream with header
po_stream = polibext . PoStream ( StringIO . StringIO ( self . po_header ) ) . parse ( )
for ( name , field ) in easymode . tree . introspection . get_default_field_descriptors ( model ) :
occurrence = u"%s.%s.%s" % ( mod... |
def gt ( self , other , axis = "columns" , level = None ) :
"""Checks element - wise that this is greater than other .
Args :
other : A DataFrame or Series or scalar to compare to .
axis : The axis to perform the gt over .
level : The Multilevel index level to apply gt over .
Returns :
A new DataFrame f... | return self . _binary_op ( "gt" , other , axis = axis , level = level ) |
def message_handler ( self , commands = None , regexp = None , func = None , content_types = [ 'text' ] , ** kwargs ) :
"""Message handler decorator .
This decorator can be used to decorate functions that must handle certain types of messages .
All message handlers are tested in the order they were added .
Ex... | def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler , commands = commands , regexp = regexp , func = func , content_types = content_types , ** kwargs )
self . add_message_handler ( handler_dict )
return handler
return decorator |
def verify_weekday ( self , now ) :
'''Verify the weekday''' | return self . weekdays == "*" or str ( now . weekday ( ) ) in self . weekdays . split ( " " ) |
def _initialize_distance_grid ( self ) :
"""Initialize the distance grid by calls to _ grid _ dist .""" | p = [ self . _grid_distance ( i ) for i in range ( self . num_neurons ) ]
return np . array ( p ) |
async def get_matches ( self , state : MatchState = MatchState . all_ ) :
"""Return the matches of the given state
| methcoro |
Args :
state : see : class : ` MatchState `
Raises :
APIException""" | matches = await self . connection ( 'GET' , 'tournaments/{}/matches' . format ( self . _tournament_id ) , state = state . value , participant_id = self . _id )
# return [ await self . _ tournament . get _ match ( m [ ' match ' ] [ ' id ' ] ) for m in matches ] 3.6 only . . .
ms = [ ]
for m in matches :
ms . append ... |
def status ( self ) :
"""Development status .""" | return { self . _acronym_status ( l ) : l for l in self . resp_text . split ( '\n' ) if l . startswith ( self . prefix_status ) } |
def _normalize_tags ( self , tags ) :
'''Coerces tags to lowercase strings
Parameters
tags : list or tuple of strings''' | lowered_str_tags = [ ]
for tag in tags :
lowered_str_tags . append ( str ( tag ) . lower ( ) )
return lowered_str_tags |
def filter_known_searchspace ( elements , seqtype , lookup , ns , ntermwildcards , deamidation ) :
"""Yields peptides from generator as long as their sequence is not found in
known search space dict . Useful for excluding peptides that are found in
e . g . ENSEMBL or similar""" | for element in elements :
seq_is_known = False
for seq in get_seqs_from_element ( element , seqtype , ns , deamidation ) :
if lookup . check_seq_exists ( seq , ntermwildcards ) :
seq_is_known = True
break
if seq_is_known :
formatting . clear_el ( element )
else :
... |
def inner ( X , Y , ip_B = None ) :
'''Euclidean and non - Euclidean inner product .
numpy . vdot only works for vectors and numpy . dot does not use the conjugate
transpose .
: param X : numpy array with ` ` shape = = ( N , m ) ` `
: param Y : numpy array with ` ` shape = = ( N , n ) ` `
: param ip _ B :... | if ip_B is None or isinstance ( ip_B , IdentityLinearOperator ) :
return numpy . dot ( X . T . conj ( ) , Y )
( N , m ) = X . shape
( _ , n ) = Y . shape
try :
B = get_linearoperator ( ( N , N ) , ip_B )
except TypeError :
return ip_B ( X , Y )
if m > n :
return numpy . dot ( ( B * X ) . T . conj ( ) , ... |
def indent ( text , prefix ) :
"""Adds ` prefix ` to the beginning of non - empty lines in ` text ` .""" | # Based on Python 3 ' s textwrap . indent
def prefixed_lines ( ) :
for line in text . splitlines ( True ) :
yield ( prefix + line if line . strip ( ) else line )
return u"" . join ( prefixed_lines ( ) ) |
def full_load ( self ) :
"""Process the data directories .
This method will load the data directories which might not have
been loaded if the " fast _ load " option was used .""" | self . parse_data_directories ( )
class RichHeader ( object ) :
pass
rich_header = self . parse_rich_header ( )
if rich_header :
self . RICH_HEADER = RichHeader ( )
self . RICH_HEADER . checksum = rich_header . get ( 'checksum' , None )
self . RICH_HEADER . values = rich_header . get ( 'values' , None )... |
def html_page_context ( cls , app , pagename , templatename , context , doctree ) :
"""Update the Jinja2 HTML context , exposes the Versions class instance to it .
: param sphinx . application . Sphinx app : Sphinx application object .
: param str pagename : Name of the page being rendered ( without . html or a... | assert templatename or doctree
# Unused , for linting .
cls . VERSIONS . context = context
versions = cls . VERSIONS
this_remote = versions [ cls . CURRENT_VERSION ]
banner_main_remote = versions [ cls . BANNER_MAIN_VERSION ] if cls . SHOW_BANNER else None
# Update Jinja2 context .
context [ 'bitbucket_version' ] = cls... |
def restore_recycle_bin ( self , fs_ids , ** kwargs ) :
"""批量还原文件或目录 ( 非强一致接口 , 调用后请sleep1秒 ) .
: param fs _ ids : 所还原的文件或目录在 PCS 的临时唯一标识 ID 的列表 。
: type fs _ ids : list or tuple
: return : requests . Response 对象""" | data = { 'fidlist' : json . dumps ( fs_ids ) }
url = 'http://{0}/api/recycle/restore' . format ( BAIDUPAN_SERVER )
return self . _request ( 'recycle' , 'restore' , data = data , ** kwargs ) |
def convert ( string , sanitize = False ) :
"""Swap characters from script to transliterated version and vice versa .
Optionally sanitize string by using preprocess function .
: param sanitize :
: param string :
: return :""" | return r . convert ( string , ( preprocess if sanitize else False ) ) |
def print_timers ( self ) :
'''PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS''' | self . timer += time ( )
total_time = self . timer
tmp = '* %s *'
debug . log ( '' , '* ' * 29 , tmp % ( ' ' * 51 ) , tmp % ( '%s %s %s' % ( 'Program Name' . ljust ( 20 ) , 'Status' . ljust ( 7 ) , 'Execute Time (H:M:S)' ) ) , tmp % ( '=' * 51 ) )
for name in self . list :
if self . exists ( name ) :
ti... |
def handle ( self ) :
"""The required handle method .""" | logger = StreamHandler . logger
logger . debug ( "handling requests with message handler %s " % StreamHandler . message_handler . __class__ . __name__ )
message_handler = StreamHandler . message_handler
try :
while True :
logger . debug ( 'waiting for more data' )
if not message_handler . handle ( s... |
def emit ( self , ** kwargs ) :
"""Emit signal by calling all connected slots .
The arguments supplied have to match the signal definition .
Args :
kwargs : Keyword arguments to be passed to connected slots .
Raises :
: exc : ` InvalidEmit ` : If arguments don ' t match signal specification .""" | self . _ensure_emit_kwargs ( kwargs )
for slot in self . slots :
slot ( ** kwargs ) |
def unfollow ( self , user_id ) :
"""Follow a user .
: param user _ id : ID of the user in question
: return : The user that were unfollowed""" | return User ( self . _client . destroy_friendship ( user_id = user_id ) . _json ) |
def update ( self , m_ag , reset = True , log = True ) :
"""Computes sensorimotor values from motor orders .
: param numpy . array m _ ag : a motor command with shape ( self . conf . m _ ndims , ) or a set of n motor commands of shape ( n , self . conf . m _ ndims )
: param bool log : emit the motor and sensory... | if reset :
self . reset ( )
if len ( array ( m_ag ) . shape ) == 1 :
s = self . one_update ( m_ag , log )
else :
s = [ ]
for m in m_ag :
s . append ( self . one_update ( m , log ) )
s = array ( s )
return s |
def new ( self , data ) :
"""通过data新建一个stock _ block
Arguments :
data { [ type ] } - - [ description ]
Returns :
[ type ] - - [ description ]""" | temp = copy ( self )
temp . __init__ ( data )
return temp |
def no_auth ( self ) :
"""Unset authentication temporarily as a context manager .""" | old_basic_auth , self . auth = self . auth , None
old_token_auth = self . headers . pop ( 'Authorization' , None )
yield
self . auth = old_basic_auth
if old_token_auth :
self . headers [ 'Authorization' ] = old_token_auth |
def parse_match_settings ( match_settings , config : ConfigObject ) :
"""Parses the matching settings modifying the match settings object .
: param match _ settings :
: param config :
: return :""" | match_settings . game_mode = config . get ( MATCH_CONFIGURATION_HEADER , GAME_MODE )
match_settings . game_map = config . get ( MATCH_CONFIGURATION_HEADER , GAME_MAP )
match_settings . skip_replays = config . getboolean ( MATCH_CONFIGURATION_HEADER , SKIP_REPLAYS )
match_settings . instant_start = config . getboolean (... |
def is_cpat_compatible ( gtf ) :
"""CPAT needs some transcripts annotated with protein coding status to work
properly""" | if not gtf :
return False
db = get_gtf_db ( gtf )
pred = lambda biotype : biotype and biotype == "protein_coding"
biotype_lookup = _biotype_lookup_fn ( gtf )
if not biotype_lookup :
return False
db = get_gtf_db ( gtf )
for feature in db . all_features ( ) :
biotype = biotype_lookup ( feature )
if pred (... |
def as_list_data ( self ) :
"""Return an Element to be used in a list .
Most lists want an element with tag of list _ type , and
subelements of id and name .
Returns :
Element : list representation of object .""" | element = ElementTree . Element ( self . list_type )
id_ = ElementTree . SubElement ( element , "id" )
id_ . text = self . id
name = ElementTree . SubElement ( element , "name" )
name . text = self . name
return element |
def close ( self ) :
"""Get results and close clamd daemon sockets .""" | self . wsock . close ( )
data = self . sock . recv ( self . sock_rcvbuf )
while data :
if "FOUND\n" in data :
self . infected . append ( data )
if "ERROR\n" in data :
self . errors . append ( data )
data = self . sock . recv ( self . sock_rcvbuf )
self . sock . close ( ) |
def _Parse ( self ) :
"""Extracts attributes and extents from the volume .""" | vshadow_store = self . _file_entry . GetVShadowStore ( )
self . _AddAttribute ( volume_system . VolumeAttribute ( 'identifier' , vshadow_store . identifier ) )
self . _AddAttribute ( volume_system . VolumeAttribute ( 'copy_identifier' , vshadow_store . copy_identifier ) )
self . _AddAttribute ( volume_system . VolumeAt... |
def _parse_normalization_kwargs ( self , use_batch_norm , batch_norm_config , normalization_ctor , normalization_kwargs ) :
"""Sets up normalization , checking old and new flags .""" | if use_batch_norm is not None : # Delete this whole block when deprecation is done .
util . deprecation_warning ( "`use_batch_norm` kwarg is deprecated. Change your code to instead " "specify `normalization_ctor` and `normalization_kwargs`." )
if not use_batch_norm : # Explicitly set to False - normalization _ ... |
def _apply ( self , ctx : ExtensionContext ) -> AugmentedDict :
"""Replaces any { { var : : * } } directives with it ' s actual variable value or a default .
Args :
ctx : The processing context .
Returns :
Returns the altered node key and value .""" | node_key , node_value = ctx . node
def process ( pattern : Pattern [ str ] , _str : str ) -> Any :
_match = pattern . match ( _str )
if _match is None :
return _str
# We got a match
# Group 0 : Whole match ; Group 1 : Our placeholder ; Group 2 : The environment variable
placeholder , varname... |
def service_command ( name , command ) :
"""Run an init . d / upstart command .""" | service_command_template = getattr ( env , 'ARGYLE_SERVICE_COMMAND_TEMPLATE' , u'/etc/init.d/%(name)s %(command)s' )
sudo ( service_command_template % { 'name' : name , 'command' : command } , pty = False ) |
def get_license_summary ( license_code ) :
"""Gets the license summary and permitted , forbidden and required
behaviour""" | try :
abs_file = os . path . join ( _ROOT , "summary.json" )
with open ( abs_file , 'r' ) as f :
summary_license = json . loads ( f . read ( ) ) [ license_code ]
# prints summary
print ( Fore . YELLOW + 'SUMMARY' )
print ( Style . RESET_ALL ) ,
print ( summary_license [ 'summary' ] )
... |
def connection_made ( self , transport : asyncio . BaseTransport ) -> None :
"""Register connection and initialize a task to handle it .""" | super ( ) . connection_made ( transport )
# Register the connection with the server before creating the handler
# task . Registering at the beginning of the handler coroutine would
# create a race condition between the creation of the task , which
# schedules its execution , and the moment the handler starts running .
... |
def get_all_compound_origins ( chebi_ids ) :
'''Returns all compound origins''' | all_compound_origins = [ get_compound_origins ( chebi_id ) for chebi_id in chebi_ids ]
return [ x for sublist in all_compound_origins for x in sublist ] |
def run_pipeline ( self , pipeline , start_date , end_date ) :
"""Compute a pipeline .
Parameters
pipeline : zipline . pipeline . Pipeline
The pipeline to run .
start _ date : pd . Timestamp
Start date of the computed matrix .
end _ date : pd . Timestamp
End date of the computed matrix .
Returns
r... | # See notes at the top of this module for a description of the
# algorithm implemented here .
if end_date < start_date :
raise ValueError ( "start_date must be before or equal to end_date \n" "start_date=%s, end_date=%s" % ( start_date , end_date ) )
domain = self . resolve_domain ( pipeline )
graph = pipeline . to... |
def fit ( self , X , y = None ) :
"""Fit the grid
Parameters
X : array - like , shape = [ n _ samples , n _ features ]
Data points
Returns
self""" | X = array2d ( X )
self . n_features = X . shape [ 1 ]
self . n_bins = self . n_bins_per_feature ** self . n_features
if self . min is None :
min = np . min ( X , axis = 0 )
elif isinstance ( self . min , numbers . Number ) :
min = self . min * np . ones ( self . n_features )
else :
min = np . asarray ( self... |
def _heavyQuery ( variantSetId , callSetIds ) :
"""Very heavy query : calls for the specified list of callSetIds
on chromosome 2 ( 11 pages , 90 seconds to fetch the entire thing
on a high - end desktop machine )""" | request = protocol . SearchVariantsRequest ( )
request . reference_name = '2'
request . variant_set_id = variantSetId
for callSetId in callSetIds :
request . call_set_ids . add ( callSetId )
request . page_size = 100
request . end = 100000
return request |
def mount_points ( self ) :
"return mount points" | wp = cq . Workplane ( "XY" )
h = wp . rect ( self . hole_spacing , self . hole_spacing , forConstruction = True ) . vertices ( )
return h . objects |
def styleMapStyleNameFallback ( info ) :
"""Fallback to * openTypeNamePreferredSubfamilyName * if
it is one of * regular * , * bold * , * italic * , * bold italic * , otherwise
fallback to * regular * .""" | styleName = getAttrWithFallback ( info , "openTypeNamePreferredSubfamilyName" )
if styleName is None :
styleName = "regular"
elif styleName . strip ( ) . lower ( ) not in _styleMapStyleNames :
styleName = "regular"
else :
styleName = styleName . strip ( ) . lower ( )
return styleName |
def _select_filepath ( self , filepath ) :
"""Make a choice between ` ` filepath ` ` and ` ` self . default _ filepath ` ` .
Args
filepath : str
the filepath to be compared with ` ` self . default _ filepath ` `
Returns
str
The selected filepath""" | if filepath is None :
return self . default_filepath
else :
if os . path . basename ( filepath ) == '' :
filepath = os . path . join ( filepath , os . path . basename ( self . default_filepath ) )
return filepath |
def _find_block_start ( self , table , used_cells , possible_block_start , start_pos , end_pos ) :
'''Finds the start of a block from a suggested start location . This location can be at a lower
column but not a lower row . The function traverses columns until it finds a stopping
condition or a repeat condition... | current_col = possible_block_start [ 1 ]
block_start = list ( possible_block_start )
block_end = list ( possible_block_start )
repeat = True
checked_all = False
# Repeat until we ' ve met satisfactory conditions for catching all edge cases or we ' ve
# checked all valid block locations
while not checked_all and repeat ... |
def clear_cache ( self , using = None , ** kwargs ) :
"""Clear all caches or specific cached associated with the index .
Any additional keyword arguments will be passed to
` ` Elasticsearch . indices . clear _ cache ` ` unchanged .""" | return self . _get_connection ( using ) . indices . clear_cache ( index = self . _name , ** kwargs ) |
def filter_out_mutations_in_normal ( tumordf , normaldf , most_common_maf_min = 0.2 , most_common_count_maf_threshold = 20 , most_common_count_min = 1 ) :
"""Remove mutations that are in normal""" | df = tumordf . merge ( normaldf , on = [ "chrom" , "pos" ] , suffixes = ( "_T" , "_N" ) )
# filters
common_al = ( df . most_common_al_count_T == df . most_common_count_T ) & ( df . most_common_al_T == df . most_common_al_N )
common_indel = ( df . most_common_indel_count_T == df . most_common_count_T ) & ( df . most_com... |
def register_microscope_files ( self , plate_name , acquisition_name , path ) :
'''Register microscope files contained in ` path ` ( Server side ) .
If ` path ` is a directory , upload all files contained in it .
Parameters
plate _ name : str
name of the parent plate
acquisition _ name : str
name of the... | logger . info ( 'register microscope files for experiment "%s", plate "%s" ' 'and acquisition "%s"' , self . experiment_name , plate_name , acquisition_name )
acquisition_id = self . _get_acquisition_id ( plate_name , acquisition_name )
register_url = self . _build_api_url ( '/experiments/{experiment_id}/acquisitions/{... |
def convert ( source_file , destination_file , cfg ) :
"""convert in every way .""" | source_ext = os . path . splitext ( source_file ) [ 1 ]
source_ext = source_ext . lower ( )
dest_ext = os . path . splitext ( destination_file ) [ 1 ]
dest_ext = dest_ext . lower ( )
if source_ext not in ( ".wav" , ".cas" , ".bas" ) :
raise AssertionError ( "Source file type %r not supported." % repr ( source_ext )... |
def _build_command ( self ) :
"""Command to start the VPCS process .
( to be passed to subprocess . Popen ( ) )
VPCS command line :
usage : vpcs [ options ] [ scriptfile ]
Option :
- h print this help then exit
- v print version information then exit
- i num number of vpc instances to start ( default ... | command = [ self . _vpcs_path ( ) ]
command . extend ( [ "-p" , str ( self . _internal_console_port ) ] )
# listen to console port
command . extend ( [ "-m" , str ( self . _manager . get_mac_id ( self . id ) ) ] )
# the unique ID is used to set the MAC address offset
command . extend ( [ "-i" , "1" ] )
# option to star... |
def add_jenkins_job_options ( parser ) :
"""Add a new job to Jenkins for updating chef - repo
: rtype : argparse . ArgumentParser""" | cookbook = parser . add_parser ( 'jenkins' , help = 'Add a new cookbook job to ' 'Jenkins' )
cookbook . add_argument ( 'jenkins' , action = 'store' , help = 'The jenkins server hostname' )
cookbook . add_argument ( 'name' , action = 'store' , help = 'The cookbook name' )
cookbook . add_argument ( 'cookbook' , action = ... |
def validate ( self , raw_data , ** kwargs ) :
"""Convert the raw _ data to an integer .""" | try :
converted_data = int ( raw_data )
return super ( IntegerField , self ) . validate ( converted_data )
except ValueError :
raise ValidationException ( self . messages [ 'invalid' ] , repr ( raw_data ) ) |
def dump_frames ( self , frame ) :
"""dumps frames chain in a representation suitable for serialization
and remote ( debugger ) client usage .""" | current_thread = threading . currentThread ( )
frames = [ ]
frame_browser = frame
# Browse the frame chain as far as we can
_logger . f_debug ( "dump_frames(), frame analysis:" )
spacer = ""
while hasattr ( frame_browser , 'f_back' ) and frame_browser . f_back != self . frame_beginning :
spacer += "="
_logger .... |
def wait_for_prompt ( self , timeout_s = None ) :
"""Wait for the user to respond to the current prompt .
Args :
timeout _ s : Seconds to wait before raising a PromptUnansweredError .
Returns :
A string response , or the empty string if text _ input was False .
Raises :
PromptUnansweredError : Timed out... | with self . _cond :
if self . _prompt :
if timeout_s is None :
self . _cond . wait ( 3600 * 24 * 365 )
else :
self . _cond . wait ( timeout_s )
if self . _response is None :
raise PromptUnansweredError
return self . _response |
def get_normal_connection ( config ) :
"""Get the connection either with a username and password or without""" | if config . username and config . password :
log . debug ( "connecting with username and password" )
queue_manager = pymqi . connect ( config . queue_manager_name , config . channel , config . host_and_port , config . username , config . password )
else :
log . debug ( "connecting without a username and pas... |
def _write_file ( self , slug , folderpath , html ) :
"""Writes a chart ' s html to a file""" | # check directories
if not os . path . isdir ( folderpath ) :
try :
os . makedirs ( folderpath )
self . info ( "Creating directory " + folderpath )
except Exception as e :
self . err ( e )
return
# construct file path
filepath = folderpath + "/" + slug + ".html"
# write the file
... |
def _read_from_folder ( self , dirname ) :
"""Internal folder reader .
: type dirname : str
: param dirname : Folder to read from .""" | templates = _par_read ( dirname = dirname , compressed = False )
t_files = glob . glob ( dirname + os . sep + '*.ms' )
tribe_cat_file = glob . glob ( os . path . join ( dirname , "tribe_cat.*" ) )
if len ( tribe_cat_file ) != 0 :
tribe_cat = read_events ( tribe_cat_file [ 0 ] )
else :
tribe_cat = Catalog ( )
pr... |
def set_label ( self , text , location = 'upper right' , style = None ) :
"""Set a label for the plot .
: param text : the label text .
: param location : the location of the label inside the plot . May
be one of ' center ' , ' upper right ' , ' lower right ' , ' upper
left ' , ' lower left ' .
: param st... | if location in RELATIVE_NODE_LOCATIONS :
label = RELATIVE_NODE_LOCATIONS [ location ] . copy ( )
label [ 'text' ] = text
label [ 'style' ] = style
self . label = label
else :
raise RuntimeError ( 'Unknown label location: %s' % location ) |
def map_crt_to_pol ( aryXCrds , aryYrds ) :
"""Remap coordinates from cartesian to polar
Parameters
aryXCrds : 1D numpy array
Array with x coordinate values .
aryYrds : 1D numpy array
Array with y coordinate values .
Returns
aryTht : 1D numpy array
Angle of coordinates
aryRad : 1D numpy array
Ra... | aryRad = np . sqrt ( aryXCrds ** 2 + aryYrds ** 2 )
aryTht = np . arctan2 ( aryYrds , aryXCrds )
return aryTht , aryRad |
def prepare_auth_headers ( session , include_cauth = False ) :
"""This function prepares headers with CSRF / CAUTH tokens that can
be used in POST requests such as login / get _ quiz .
@ param session : Requests session .
@ type session : requests . Session
@ param include _ cauth : Flag that indicates whet... | # csrftoken is simply a 20 char random string .
csrftoken = random_string ( 20 )
# Now make a call to the authenticator url .
csrf2cookie = 'csrf2_token_%s' % random_string ( 8 )
csrf2token = random_string ( 24 )
cookie = "csrftoken=%s; %s=%s" % ( csrftoken , csrf2cookie , csrf2token )
if include_cauth :
CAUTH = se... |
def event_log_filter_between_date ( start , end , utc ) :
"""betweenDate Query filter that SoftLayer _ EventLog likes
: param string start : lower bound date in mm / dd / yyyy format
: param string end : upper bound date in mm / dd / yyyy format
: param string utc : utc offset . Defaults to ' + 0000'""" | return { 'operation' : 'betweenDate' , 'options' : [ { 'name' : 'startDate' , 'value' : [ format_event_log_date ( start , utc ) ] } , { 'name' : 'endDate' , 'value' : [ format_event_log_date ( end , utc ) ] } ] } |
def open ( self , path , filename = None ) :
"""Open a file specified by path .""" | scheme , key = self . getkey ( path , filename = filename )
return BotoReadFileHandle ( scheme , key ) |
def _get_indexing_dispatch_code ( key ) :
"""Returns a dispatch code for calling basic or advanced indexing functions .""" | if isinstance ( key , ( NDArray , np . ndarray ) ) :
return _NDARRAY_ADVANCED_INDEXING
elif isinstance ( key , list ) : # TODO ( junwu ) : Add support for nested lists besides integer list
for i in key :
if not isinstance ( i , integer_types ) :
raise TypeError ( 'Indexing NDArray only suppo... |
def manage_signal ( self , sig , frame ) : # pylint : disable = unused - argument
"""Manage signals caught by the process but I do not do anything . . .
our master daemon is managing our termination .
: param sig : signal caught by daemon
: type sig : str
: param frame : current stack frame
: type frame :... | logger . info ( "worker '%s' (pid=%d) received a signal: %s" , self . _id , os . getpid ( ) , SIGNALS_TO_NAMES_DICT [ sig ] )
# Do not do anything . . . our master daemon is managing our termination .
self . interrupted = True |
def get_specificity ( self , scalar = None ) :
"""True _ Negative / ( True _ Negative + False _ Positive )""" | if ( ( not self . _scalar_stats and not scalar and self . _num_classes > 2 ) or ( ( scalar is False or self . _scalar_stats is False ) and self . _num_classes > 1 ) ) :
spec = PrettyDict ( )
for pos_label in self . columns :
neg_labels = [ label for label in self . columns if label != pos_label ]
... |
def clip ( self , min = None , max = None ) :
"""Clip values above and below .
Parameters
min : scalar or array - like
Minimum value . If array , will be broadcasted
max : scalar or array - like
Maximum value . If array , will be broadcasted .""" | return self . _constructor ( self . values . clip ( min = min , max = max ) ) . __finalize__ ( self ) |
def draw_chimera_embedding ( G , * args , ** kwargs ) :
"""Draws an embedding onto the chimera graph G , according to layout .
If interaction _ edges is not None , then only display the couplers in that
list . If embedded _ graph is not None , the only display the couplers between
chains with intended couplin... | draw_embedding ( G , chimera_layout ( G ) , * args , ** kwargs ) |
def get_active ( ) -> List [ str ] :
"""Return the list of active subarrays .""" | active = [ ]
for i in range ( __num_subarrays__ ) :
key = Subarray . get_key ( i )
if DB . get_hash_value ( key , 'active' ) . upper ( ) == 'TRUE' :
active . append ( Subarray . get_id ( i ) )
return active |
def t_lumi ( self , num_frame , xax ) :
"""Luminosity evolution as a function of time or model .
Parameters
num _ frame : integer
Number of frame to plot this plot into .
xax : string
Either model or time to indicate what is to be used on the
x - axis""" | pyl . figure ( num_frame )
if xax == 'time' :
xaxisarray = self . get ( 'star_age' )
elif xax == 'model' :
xaxisarray = self . get ( 'model_number' )
else :
print ( 'kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"' )
logLH = self . get ( 'log_LH' )
logLHe = self . get ( '... |
def visit_Assign ( self , node ) :
"""Visit an assignment node .""" | line = self . _code_lines [ node . lineno - 1 ]
if SIG_COMMENT in line :
line = _RE_COMMENT_IN_STRING . sub ( "" , line )
if ( SIG_COMMENT not in line ) and ( not self . generic ) :
return
if SIG_COMMENT in line :
_ , signature = line . split ( SIG_COMMENT )
_ , return_type , requires = parse_signature ... |
def kill_all ( self , kill_signal , kill_shell = False ) :
"""Kill all running processes .""" | for key in self . processes . keys ( ) :
self . kill_process ( key , kill_signal , kill_shell ) |
def getLoggingLocation ( self ) :
"""Return the path for the calcpkg . log file - at the moment , only use a Linux path since I don ' t know where Windows thinks logs should go .""" | if sys . platform == "win32" :
modulePath = os . path . realpath ( __file__ )
modulePath = modulePath [ : modulePath . rfind ( "/" ) ]
return modulePath
else :
return "/tmp"
return "" |
def tile ( self , z_x_y ) :
"""Return the tile ( binary ) content of the tile and seed the cache .""" | ( z , x , y ) = z_x_y
logger . debug ( _ ( "tile method called with %s" ) % ( [ z , x , y ] ) )
output = self . cache . read ( ( z , x , y ) )
if output is None :
output = self . reader . tile ( z , x , y )
# Blend layers
if len ( self . _layers ) > 0 :
logger . debug ( _ ( "Will blend %s layer(s)" ... |
def main ( ) :
"""Main function for pyfttt command line tool""" | args = parse_arguments ( )
if args . key is None :
print ( "Error: Must provide IFTTT secret key." )
sys . exit ( 1 )
try :
res = pyfttt . send_event ( api_key = args . key , event = args . event , value1 = args . value1 , value2 = args . value2 , value3 = args . value3 )
except requests . exceptions . Conn... |
def cal_pst ( self , v ) :
"""calculate static pressure at 300 K .
: param v : unit - cell volume in A ^ 3
: return : static pressure at t _ ref ( = 300 K ) in GPa""" | params = self . _set_params ( self . params_st )
return func_st [ self . eqn_st ] ( v , * params ) |
def parse_block ( self , stream , has_end ) :
"""PVLModuleContents : : = ( Statement | WSC ) * EndStatement ?
AggrObject : : = BeginObjectStmt AggrContents EndObjectStmt
AggrGroup : : = BeginGroupStmt AggrContents EndGroupStmt
AggrContents : = WSC Statement ( WSC | Statement ) *""" | statements = [ ]
while 1 :
self . skip_whitespace_or_comment ( stream )
if has_end ( stream ) :
return statements
statement = self . parse_statement ( stream )
if isinstance ( statement , EmptyValueAtLine ) :
if len ( statements ) == 0 :
self . raise_unexpected ( stream )
... |
def is_atlas_enabled ( blockstack_opts ) :
"""Can we do atlas operations ?""" | if not blockstack_opts [ 'atlas' ] :
log . debug ( "Atlas is disabled" )
return False
if 'zonefiles' not in blockstack_opts :
log . debug ( "Atlas is disabled: no 'zonefiles' path set" )
return False
if 'atlasdb_path' not in blockstack_opts :
log . debug ( "Atlas is disabled: no 'atlasdb_path' path ... |
def fftshift ( arr_obj , axes = None , res_g = None , return_buffer = False ) :
"""gpu version of fftshift for numpy arrays or OCLArrays
Parameters
arr _ obj : numpy array or OCLArray ( float32 / complex64)
the array to be fftshifted
axes : list or None
the axes over which to shift ( like np . fft . fftsh... | if axes is None :
axes = list ( range ( arr_obj . ndim ) )
if isinstance ( arr_obj , OCLArray ) :
if not arr_obj . dtype . type in DTYPE_KERNEL_NAMES :
raise NotImplementedError ( "only works for float32 or complex64" )
elif isinstance ( arr_obj , np . ndarray ) :
if np . iscomplexobj ( arr_obj ) :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.