signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def display_package_changes ( pre_packages , post_packages , indent = '' ) :
"""Print packages that ' ve been added , removed or changed""" | # use package name to determine what ' s changed
pre_package_names = { p . name : p for p in pre_packages }
post_package_names = { p . name : p for p in post_packages }
added = set ( post_package_names . keys ( ) ) - set ( pre_package_names . keys ( ) )
removed = set ( pre_package_names . keys ( ) ) - set ( post_packag... |
def predict ( self , features ) :
"""Predict class outputs for an unlabelled feature set""" | # get distance of features to class clusters
distances = [ self . _distance ( x ) for x in features ]
# assign class label belonging to smallest distance
class_predict = [ np . argmin ( d ) for d in distances ]
return self . le . inverse_transform ( class_predict ) |
def _points ( self , x_pos ) :
"""Convert given data values into drawable points ( x , y )
and interpolated points if interpolate option is specified""" | for series_group in ( self . series , self . secondary_series ) :
accumulation = [ 0 ] * self . _len
for serie in series_group [ : : - 1 if self . stack_from_top else 1 ] :
accumulation = list ( map ( sum , zip ( accumulation , serie . values ) ) )
serie . points = [ ( x_pos [ i ] , v ) for i , ... |
def _is_group ( token ) :
"""sqlparse 0.2.2 changed it from a callable to a bool property""" | is_group = token . is_group
if isinstance ( is_group , bool ) :
return is_group
else :
return is_group ( ) |
def _sequence_range_check ( self , result , last ) :
"""If range backwards , remove it .
A bad range will cause the regular expression to fail ,
so we need to remove it , but return that we removed it
so the caller can know the sequence wasn ' t empty .
Caller will have to craft a sequence that makes sense ... | removed = False
first = result [ - 2 ]
v1 = ord ( first [ 1 : 2 ] if len ( first ) > 1 else first )
v2 = ord ( last [ 1 : 2 ] if len ( last ) > 1 else last )
if v2 < v1 :
result . pop ( )
result . pop ( )
removed = True
else :
result . append ( last )
return removed |
def slice_faces_plane ( vertices , faces , plane_normal , plane_origin , cached_dots = None ) :
"""Slice a mesh ( given as a set of faces and vertices ) with a plane , returning a
new mesh ( again as a set of faces and vertices ) that is the
portion of the original mesh to the positive normal side of the plane ... | if len ( vertices ) == 0 :
return vertices , faces
if cached_dots is not None :
dots = cached_dots
else : # dot product of each vertex with the plane normal indexed by face
# so for each face the dot product of each vertex is a row
# shape is the same as faces ( n , 3)
dots = np . einsum ( 'i,ij->j' , plane... |
def _remove_trailing_empty_p ( self ) :
"""Remove the last content element from this cell if it is an empty
` ` < w : p > ` ` element .""" | block_items = list ( self . iter_block_items ( ) )
last_content_elm = block_items [ - 1 ]
if last_content_elm . tag != qn ( 'w:p' ) :
return
p = last_content_elm
if len ( p . r_lst ) > 0 :
return
self . remove ( p ) |
def clean_doi ( doi_string ) :
"""Use regex to extract all DOI ids from string ( i . e . 10.1029/2005pa001215)
: param str doi _ string : Raw DOI string value from input file . Often not properly formatted .
: return list : DOI ids . May contain 0 , 1 , or multiple ids .""" | regex = re . compile ( r'\b(10[.][0-9]{3,}(?:[.][0-9]+)*/(?:(?!["&\'<>,])\S)+)\b' )
try : # Returns a list of matching strings
m = re . findall ( regex , doi_string )
except TypeError as e : # If doi _ string is None type , return empty list
logger_misc . warn ( "TypeError cleaning DOI: {}, {}" . format ( doi_s... |
def show_colormaps ( names = [ ] , N = 10 , show = True , use_qt = None ) :
"""Function to show standard colormaps from pyplot
Parameters
` ` * args ` ` : str or : class : ` matplotlib . colors . Colormap `
If a colormap , it returned unchanged .
% ( cmap _ note ) s
N : int , optional
Default : 11 . The... | names = safe_list ( names )
if use_qt or ( use_qt is None and psyplot . with_gui ) :
from psy_simple . widgets . colors import ColormapDialog
from psyplot_gui . main import mainwindow
return ColormapDialog . show_colormap ( names , N , show , parent = mainwindow )
import matplotlib . pyplot as plt
# This ex... |
def obj_in_list_always ( target_list , obj ) :
"""> > > l = [ 1,1,1]
> > > obj _ in _ list _ always ( l , 1)
True
> > > l . append ( 2)
> > > obj _ in _ list _ always ( l , 1)
False""" | for item in set ( target_list ) :
if item is not obj :
return False
return True |
def list_queues ( region , opts = None , user = None ) :
'''List the queues in the selected region .
region
Region to list SQS queues for
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
CLI Example :
salt ' * ' aws _ sqs .... | out = _run_aws ( 'list-queues' , region , opts , user )
ret = { 'retcode' : 0 , 'stdout' : out [ 'QueueUrls' ] , }
return ret |
def connect_ses ( aws_access_key_id = None , aws_secret_access_key = None , ** kwargs ) :
""": type aws _ access _ key _ id : string
: param aws _ access _ key _ id : Your AWS Access Key ID
: type aws _ secret _ access _ key : string
: param aws _ secret _ access _ key : Your AWS Secret Access Key
: rtype :... | from boto . ses import SESConnection
return SESConnection ( aws_access_key_id , aws_secret_access_key , ** kwargs ) |
def clean ( self ) :
"""Delete temp dir if not save _ temp set at _ _ init _ _""" | if not self . _save_temp :
if hasattr ( self , '_written_files' ) :
map ( os . unlink , self . _written_files )
if getattr ( self , '_remove_tempdir_on_clean' , False ) :
shutil . rmtree ( self . _tempdir ) |
def get_catalog_lookup_session ( self ) :
"""Gets the catalog lookup session .
return : ( osid . cataloging . CatalogLookupSession ) - a
` ` CatalogLookupSession ` `
raise : OperationFailed - unable to complete request
raise : Unimplemented - ` ` supports _ catalog _ lookup ( ) ` ` is
` ` false ` `
* co... | if not self . supports_catalog_lookup ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . CatalogLookupSession ( runtime = self . _runtime ) |
def blind ( m , hashfunc = hashG1 ) :
"""Blinds an arbitrary string or byte array @ m using an ephemeral key @ r
that can be used to deblind . Computes : x = H ( x ) ^ r
@ returns ( 1 / r , x )""" | # Find r with a suitable inverse in Gt
rInv = None
while not rInv :
r = randomZ ( )
rInv = inverse ( r , orderGt ( ) )
return rInv , hashfunc ( m ) * r |
def get_objects_with_attribute ( self , obj_type , attribute , value ) :
""": param obj _ type : requested object type .
: param attribute : requested attribute .
: param value : requested attribute value .
: return : all children of the requested type that have the requested attribute = = requested value .""... | return [ o for o in self . get_objects_by_type ( obj_type ) if o . get_attribute ( attribute ) == value ] |
def primary_keys_for ( self , cls : ClassDefinition ) -> List [ SlotDefinitionName ] :
"""Return all primary keys / identifiers for cls
@ param cls : class to get keys for
@ return : List of primary keys""" | return [ slot_name for slot_name in self . all_slots_for ( cls ) if self . schema . slots [ slot_name ] . primary_key or self . schema . slots [ slot_name ] . identifier ] |
def define_logger_func ( self , level , field_names , default = NO_DEFAULT , filters = None , include_exc_info = False ) :
"""Define a new logger function that will log the given arguments
with the given predefined keys .
: param level :
The log level to use for each call .
: param field _ names :
Set of ... | kv_formatter = KvFormatter ( field_names , default , filters )
return lambda * a , ** kw : self . _log ( level , kv_formatter ( * a , ** kw ) , include_exc_info ) |
def execute_task ( self , task , parent_result ) :
"""Run a single task in another process saving the result to our list of pending results .
: param task : Task : function and data we can run in another process
: param parent _ result : object : result from our parent task""" | task . before_run ( parent_result )
context = task . create_context ( self . message_queue )
pending_result = self . pool . apply_async ( execute_task_async , ( task . func , task . id , context ) )
self . pending_results . append ( pending_result ) |
def send_command ( self , command ) :
"""Sends a given command to the HAProxy control socket .
Returns the response from the socket as a string .
If a known error response ( e . g . " Permission denied . " ) is given then
the appropriate exception is raised .""" | logger . debug ( "Connecting to socket %s" , self . socket_file_path )
sock = socket . socket ( socket . AF_UNIX , socket . SOCK_STREAM )
try :
sock . connect ( self . socket_file_path )
except IOError as e :
if e . errno == errno . ECONNREFUSED :
logger . error ( "Connection refused. Is HAProxy runnin... |
def generate_totp ( secret , period = 30 , timestamp = None ) :
"""Generate a TOTP code .
A TOTP code is an extension of HOTP algorithm .
: param secret : A secret token for the authentication .
: param period : A period that a TOTP code is valid in seconds
: param timestamp : Current time stamp .""" | if timestamp is None :
timestamp = time . time ( )
counter = int ( timestamp ) // period
return generate_hotp ( secret , counter ) |
def focusOutEvent ( self , event ) :
"""Processes when this widget loses focus .
: param event | < QFocusEvent >""" | if not self . signalsBlocked ( ) :
self . focusChanged . emit ( False )
self . focusExited . emit ( )
return super ( XTextEdit , self ) . focusOutEvent ( event ) |
def render_reaction ( self , glob_ref , tag , data ) :
'''Execute the render system against a single reaction file and return
the data structure''' | react = { }
if glob_ref . startswith ( 'salt://' ) :
glob_ref = self . minion . functions [ 'cp.cache_file' ] ( glob_ref ) or ''
globbed_ref = glob . glob ( glob_ref )
if not globbed_ref :
log . error ( 'Can not render SLS %s for tag %s. File missing or not found.' , glob_ref , tag )
for fn_ in globbed_ref :
... |
def get_or_none ( cls , mp , part_number ) :
"""Get part number .""" | return cls . query . filter_by ( upload_id = mp . upload_id , part_number = part_number ) . one_or_none ( ) |
def unregister_identity ( self , category , type_ ) :
"""Unregister an identity previously registered using
: meth : ` register _ identity ` .
If no identity with the given ` category ` and ` type _ ` has been
registered before , : class : ` KeyError ` is raised .
If the identity to remove is the last ident... | key = category , type_
if key not in self . _identities :
raise KeyError ( key )
if len ( self . _identities ) == 1 :
raise ValueError ( "cannot remove last identity" )
del self . _identities [ key ]
self . on_info_changed ( ) |
def _is_already_configured ( configuration_details ) :
"""Returns ` True ` when alias already in shell config .""" | path = Path ( configuration_details . path ) . expanduser ( )
with path . open ( 'r' ) as shell_config :
return configuration_details . content in shell_config . read ( ) |
def _unescape_value ( value ) :
"""Unescape a value .""" | def unescape ( c ) :
return { "\\\\" : "\\" , "\\\"" : "\"" , "\\n" : "\n" , "\\t" : "\t" , "\\b" : "\b" , } [ c . group ( 0 ) ]
return re . sub ( r"(\\.)" , unescape , value ) |
def get_user_id ( user_id_or_username ) :
"""Gets the user ID based on the value ` user _ id _ or _ username ` specified on
the command - line , being extra lenient and lowercasing the value in all
cases .""" | user_id_or_username = user_id_or_username . lower ( )
if not user_id_or_username . startswith ( "user-" ) :
user_id = "user-" + user_id_or_username . lower ( )
else :
user_id = user_id_or_username
return user_id |
def execute ( self ) :
"""Resolves the specified confs for the configured targets and returns an iterator over
tuples of ( conf , jar path ) .""" | jvm_resolve_subsystem = JvmResolveSubsystem . global_instance ( )
if jvm_resolve_subsystem . get_options ( ) . resolver != 'coursier' :
return
# executor = self . create _ java _ executor ( )
classpath_products = self . context . products . get_data ( 'compile_classpath' , init_func = ClasspathProducts . init_func ... |
from typing import List
def rolling_maximums ( numbers : List [ int ] ) -> List [ int ] :
"""Get a list where each item is the highest number seen so far in the input list .
Example :
> > > rolling _ maximums ( [ 1 , 2 , 3 , 2 , 3 , 4 , 2 ] )
[1 , 2 , 3 , 3 , 3 , 4 , 4]""" | max_so_far = float ( '-inf' )
result = [ ]
for num in numbers :
max_so_far = max ( max_so_far , num )
result . append ( max_so_far )
return result |
def send_message ( self , message , icon_path = None ) :
"""Show a floating message .""" | icon_encoded_string = ''
icon_extension = ''
if icon_path is not None :
icon_extension = os . path . splitext ( icon_path ) [ 1 ] [ 1 : ]
with open ( icon_path , 'rb' ) as icon_file :
icon_encoded_string = base64 . b64encode ( icon_file . read ( ) ) . decode ( 'ascii' )
self . request ( EP_SHOW_MESSAGE ... |
def orip ( ip , rc = None , r = None , fl = None , fs = None , ot = None , coe = None , moc = None ) : # pylint : disable = too - many - arguments , redefined - outer - name , invalid - name
"""This function is a wrapper for
: meth : ` ~ pywbem . WBEMConnection . OpenReferenceInstancePaths ` .
Open an enumerati... | return CONN . OpenReferenceInstancePaths ( ip , ResultClass = rc , Role = r , FilterQueryLanguage = fl , FilterQuery = fs , OperationTimeout = ot , ContinueOnError = coe , MaxObjectCount = moc ) |
def usage_records ( self ) :
"""Access the usage _ records
: returns : twilio . rest . wireless . v1 . sim . usage _ record . UsageRecordList
: rtype : twilio . rest . wireless . v1 . sim . usage _ record . UsageRecordList""" | if self . _usage_records is None :
self . _usage_records = UsageRecordList ( self . _version , sim_sid = self . _solution [ 'sid' ] , )
return self . _usage_records |
def fit ( self , data ) :
"""Get the modality assignments of each splicing event in the data
Parameters
data : pandas . DataFrame
A ( n _ samples , n _ events ) dataframe of splicing events ' PSI scores .
Must be psi scores which range from 0 to 1
Returns
log2 _ bayes _ factors : pandas . DataFrame
A ... | self . assert_less_than_or_equal_1 ( data . values . flat )
self . assert_non_negative ( data . values . flat )
if isinstance ( data , pd . DataFrame ) :
log2_bayes_factors = data . apply ( self . single_feature_fit )
elif isinstance ( data , pd . Series ) :
log2_bayes_factors = self . single_feature_fit ( data... |
def set_xylims ( self , lims , axes = None , panel = 'top' , ** kws ) :
"""set xy limits""" | panel = self . get_panel ( panel )
# print ( " Stacked set _ xylims " , panel , self . panel )
panel . set_xylims ( lims , axes = axes , ** kws ) |
def _close ( self , args ) :
"""request a channel close
This method indicates that the sender wants to close the
channel . This may be due to internal conditions ( e . g . a forced
shut - down ) or due to an error handling a specific method , i . e .
an exception . When a close is due to an exception , the ... | reply_code = args . read_short ( )
reply_text = args . read_shortstr ( )
class_id = args . read_short ( )
method_id = args . read_short ( )
# self . close _ ok ( )
# def close _ ok ( self ) :
# confirm a channel close
# This method confirms a Channel . Close method and tells the
# recipient that it is safe to release r... |
def toLily ( self ) :
'''Method which converts the object instance , its attributes and children to a string of lilypond code
: return : str of lilypond code''' | lilystring = ""
if not self . autoBeam :
lilystring += "\\autoBeamOff"
children = self . SortedChildren ( )
if not hasattr ( self , "transpose" ) :
self . transpose = None
for child in range ( len ( children ) ) :
measureNode = self . GetChild ( children [ child ] )
measureNode . autoBeam = self . autoB... |
def revert_to_clear ( tds_sock ) :
"""Reverts connection back to non - encrypted mode
Used when client sent ENCRYPT _ OFF flag
@ param tds _ sock :
@ return :""" | enc_conn = tds_sock . conn . sock
clear_conn = enc_conn . _transport
enc_conn . shutdown ( )
tds_sock . conn . sock = clear_conn
tds_sock . _writer . _transport = clear_conn
tds_sock . _reader . _transport = clear_conn |
def get_or_create_organization ( self , id = None , name = None ) :
"""Gets existing or creates new organization
: rtype : Organization""" | if id :
return self . get_organization ( id )
else :
assert name
try :
return self . get_organization ( name = name )
except exceptions . NotFoundError :
return self . create_organization ( name ) |
def merge_labeled_intervals ( x_intervals , x_labels , y_intervals , y_labels ) :
r"""Merge the time intervals of two sequences .
Parameters
x _ intervals : np . ndarray
Array of interval times ( seconds )
x _ labels : list or None
List of labels
y _ intervals : np . ndarray
Array of interval times ( ... | align_check = [ x_intervals [ 0 , 0 ] == y_intervals [ 0 , 0 ] , x_intervals [ - 1 , 1 ] == y_intervals [ - 1 , 1 ] ]
if False in align_check :
raise ValueError ( "Time intervals do not align; did you mean to call " "'adjust_intervals()' first?" )
time_boundaries = np . unique ( np . concatenate ( [ x_intervals , y... |
def printBasicInfo ( onto ) :
"""Terminal printing of basic ontology information""" | rdfGraph = onto . rdfGraph
print ( "_" * 50 , "\n" )
print ( "TRIPLES = %s" % len ( rdfGraph ) )
print ( "_" * 50 )
print ( "\nNAMESPACES:\n" )
for x in onto . ontologyNamespaces :
print ( "%s : %s" % ( x [ 0 ] , x [ 1 ] ) )
print ( "_" * 50 , "\n" )
print ( "ONTOLOGY METADATA:\n" )
for x , y in onto . ontologyAnno... |
def _log_to_stderr ( self , record ) :
"""Emits the record to stderr .
This temporarily sets the handler stream to stderr , calls
StreamHandler . emit , then reverts the stream back .
Args :
record : logging . LogRecord , the record to log .""" | # emit ( ) is protected by a lock in logging . Handler , so we don ' t need to
# protect here again .
old_stream = self . stream
self . stream = sys . stderr
try :
super ( PythonHandler , self ) . emit ( record )
finally :
self . stream = old_stream |
def format_row ( self , row ) :
"""Apply overflow , justification and padding to a row . Returns lines
( plural ) of rendered text for the row .""" | assert all ( isinstance ( x , VTMLBuffer ) for x in row )
raw = ( fn ( x ) for x , fn in zip ( row , self . formatters ) )
for line in itertools . zip_longest ( * raw ) :
line = list ( line )
for i , col in enumerate ( line ) :
if col is None :
line [ i ] = self . _get_blank_cell ( i )
y... |
def genus_specific ( self ) :
"""For genus - specific targets , MLST and serotyping , determine if the closest refseq genus is known - i . e . if 16S
analyses have been performed . Perform the analyses if required""" | # Initialise a variable to store whether the necessary analyses have already been performed
closestrefseqgenus = False
for sample in self . runmetadata . samples :
if sample . general . bestassemblyfile != 'NA' :
try :
closestrefseqgenus = sample . general . closestrefseqgenus
except Att... |
def ssa ( n , h , K , f , T ) :
"""ssa - - multi - stage ( serial ) safety stock allocation model
Parameters :
- n : number of stages
- h [ i ] : inventory cost on stage i
- K : number of linear segments
- f : ( non - linear ) cost function
- T [ i ] : production lead time on stage i
Returns the model... | model = Model ( "safety stock allocation" )
# calculate endpoints for linear segments
a , b = { } , { }
for i in range ( 1 , n + 1 ) :
a [ i ] = [ k for k in range ( K ) ]
b [ i ] = [ f ( i , k ) for k in range ( K ) ]
# x : net replenishment time for stage i
# y : corresponding cost
# s : piecewise linear segm... |
def set_framecolor ( self , color ) :
"""set color for outer frame""" | self . framecolor = color
self . canvas . figure . set_facecolor ( color )
if callable ( self . theme_color_callback ) :
self . theme_color_callback ( color , 'frame' ) |
def price_oscillator ( data , short_period , long_period ) :
"""Price Oscillator .
Formula :
( short EMA - long EMA / long EMA ) * 100""" | catch_errors . check_for_period_error ( data , short_period )
catch_errors . check_for_period_error ( data , long_period )
ema_short = ema ( data , short_period )
ema_long = ema ( data , long_period )
po = ( ( ema_short - ema_long ) / ema_long ) * 100
return po |
def _check_response_for_request_errors ( self ) :
"""Checks the response to see if there were any errors specific to
this WSDL .""" | if self . response . HighestSeverity == "ERROR" :
for notification in self . response . Notifications : # pragma : no cover
if notification . Severity == "ERROR" :
if "Postal Code Not Found" in notification . Message :
raise FedexPostalCodeNotFound ( notification . Code , notific... |
def verify_service ( self , service_id , specification = None , description = None , agent_mapping = None ) :
'''verify _ service ( self , service _ id , specification = None , description = None , agent _ mapping = None )
| Verifies validity of service yaml
: Parameters :
* * service _ id * ( ` string ` ) - ... | request_data = { 'id' : service_id }
if specification :
request_data [ 'spec' ] = specification
if description :
request_data [ 'description' ] = description
if agent_mapping :
request_data [ 'agents' ] = agent_mapping
return self . _call_rest_api ( 'post' , '/services/verify' , data = request_data , error ... |
def dirsearch ( word , obj , only_keys = True , deep = 0 ) :
"""search a string in dir ( < some object > )
if object is a dict , then search in keys
optional arg only _ keys : if False , returns also a str - version of
the attribute ( or dict - value ) instead only the key
this function is not case sensitiv... | word = word . lower ( )
if isinstance ( obj , dict ) : # only consider keys which are basestrings
items = [ ( key , val ) for key , val in list ( obj . items ( ) ) if isinstance ( key , str ) ]
else : # d = dir ( obj )
items = [ ]
for key in dir ( obj ) :
try :
items . append ( ( key , g... |
def csv ( ticker , path = 'data.csv' , field = '' , mrefresh = False , ** kwargs ) :
"""Data provider wrapper around pandas ' read _ csv . Provides memoization .""" | # set defaults if not specified
if 'index_col' not in kwargs :
kwargs [ 'index_col' ] = 0
if 'parse_dates' not in kwargs :
kwargs [ 'parse_dates' ] = True
# read in dataframe from csv file
df = pd . read_csv ( path , ** kwargs )
tf = ticker
if field is not '' and field is not None :
tf = '%s:%s' % ( tf , fi... |
def alternative_full_name ( self , name = None , entry_name = None , limit = None , as_df = False ) :
"""Method to query : class : ` . models . AlternativeFullName ` objects in database
: param name : alternative full name ( s )
: type name : str or tuple ( str ) or None
: param entry _ name : name ( s ) in :... | q = self . session . query ( models . AlternativeFullName )
model_queries_config = ( ( name , models . AlternativeFullName . name ) , )
q = self . get_model_queries ( q , model_queries_config )
q = self . get_one_to_many_queries ( q , ( ( entry_name , models . Entry . name ) , ) )
return self . _limit_and_df ( q , limi... |
def fpn_model ( features ) :
"""Args :
features ( [ tf . Tensor ] ) : ResNet features c2 - c5
Returns :
[ tf . Tensor ] : FPN features p2 - p6""" | assert len ( features ) == 4 , features
num_channel = cfg . FPN . NUM_CHANNEL
use_gn = cfg . FPN . NORM == 'GN'
def upsample2x ( name , x ) :
return FixedUnPooling ( name , x , 2 , unpool_mat = np . ones ( ( 2 , 2 ) , dtype = 'float32' ) , data_format = 'channels_first' )
# tf . image . resize is , again , not ... |
def contains_version ( self , version ) :
"""Returns True if version is contained in this range .""" | if len ( self . bounds ) < 5 : # not worth overhead of binary search
for bound in self . bounds :
i = bound . version_containment ( version )
if i == 0 :
return True
if i == - 1 :
return False
else :
_ , contains = self . _contains_version ( version )
return c... |
def add_section ( self , section ) :
"""Create a new section in the configuration .
Raise DuplicateSectionError if a section by the specified name
already exists . Raise ValueError if name is DEFAULT or any of it ' s
case - insensitive variants .""" | if section . lower ( ) == "default" :
raise ValueError ( 'Invalid section name: %s' % section )
if section in self . _sections :
raise DuplicateSectionError ( section )
self . _sections [ section ] = self . _dict ( ) |
def clip_boxes ( boxes , shape ) :
"""Args :
boxes : ( . . . ) x4 , float
shape : h , w""" | orig_shape = boxes . shape
boxes = boxes . reshape ( [ - 1 , 4 ] )
h , w = shape
boxes [ : , [ 0 , 1 ] ] = np . maximum ( boxes [ : , [ 0 , 1 ] ] , 0 )
boxes [ : , 2 ] = np . minimum ( boxes [ : , 2 ] , w )
boxes [ : , 3 ] = np . minimum ( boxes [ : , 3 ] , h )
return boxes . reshape ( orig_shape ) |
def _reshape_data ( self , new_size , bin_map , axis = 0 ) :
"""Reshape data to match new binning schema .
Fills frequencies and errors with 0.
Parameters
new _ size : int
bin _ map : Iterable [ ( old , new ) ] or int or None
If None , we can keep the data unchanged .
If int , it is offset by which to s... | if bin_map is None :
return
else :
new_shape = list ( self . shape )
new_shape [ axis ] = new_size
new_frequencies = np . zeros ( new_shape , dtype = self . _frequencies . dtype )
new_errors2 = np . zeros ( new_shape , dtype = self . _frequencies . dtype )
self . _apply_bin_map ( old_frequencies... |
def scale_degree_to_bitmap ( scale_degree , modulo = False , length = BITMAP_LENGTH ) :
"""Create a bitmap representation of a scale degree .
Note that values in the bitmap may be negative , indicating that the
semitone is to be removed .
Parameters
scale _ degree : str
Spelling of a relative scale degree... | sign = 1
if scale_degree . startswith ( "*" ) :
sign = - 1
scale_degree = scale_degree . strip ( "*" )
edit_map = [ 0 ] * length
sd_idx = scale_degree_to_semitone ( scale_degree )
if sd_idx < length or modulo :
edit_map [ sd_idx % length ] = sign
return np . array ( edit_map ) |
def get ( self , ** kwargs ) :
"""Same as search , but will throw an error if there are multiple or no
results . If there are multiple results and only one is an exact match
on api _ version , that resource will be returned .""" | results = self . search ( ** kwargs )
# If there are multiple matches , prefer exact matches on api _ version
if len ( results ) > 1 and kwargs . get ( 'api_version' ) :
results = [ result for result in results if result . group_version == kwargs [ 'api_version' ] ]
# If there are multiple matches , prefer non - Li... |
def get_gitignore_template ( self , name ) :
""": calls : ` GET / gitignore / templates / : name < http : / / developer . github . com / v3 / gitignore > ` _
: rtype : : class : ` github . GitignoreTemplate . GitignoreTemplate `""" | assert isinstance ( name , ( str , unicode ) ) , name
headers , attributes = self . __requester . requestJsonAndCheck ( "GET" , "/gitignore/templates/" + name )
return GitignoreTemplate . GitignoreTemplate ( self . __requester , headers , attributes , completed = True ) |
def pool_lookup ( hypervisor , disk_path ) :
"""Storage pool lookup .
Retrieves the the virStoragepool which contains the disk at the given path .""" | try :
volume = hypervisor . storageVolLookupByPath ( disk_path )
return volume . storagePoolLookupByVolume ( )
except libvirt . libvirtError :
return None |
def _get_session ( self , session ) :
"""Creates a new session with basic auth , unless one was provided , and sets headers .
: param session : ( optional ) Session to re - use
: return :
- : class : ` requests . Session ` object""" | if not session :
logger . debug ( '(SESSION_CREATE) User: %s' % self . _user )
s = requests . Session ( )
s . auth = HTTPBasicAuth ( self . _user , self . _password )
else :
logger . debug ( '(SESSION_CREATE) Object: %s' % session )
s = session
s . headers . update ( { 'content-type' : 'application/... |
def _start_of_century ( self ) :
"""Reset the date to the first day of the century .
: rtype : Date""" | year = self . year - 1 - ( self . year - 1 ) % YEARS_PER_CENTURY + 1
return self . set ( year , 1 , 1 ) |
def saveCopy ( self ) :
"saves a copy of the object and become that copy . returns a tuple ( old _ key , new _ key )" | old_key = self . _key
self . reset ( self . collection )
self . save ( )
return ( old_key , self . _key ) |
def repr_dict ( _dict , indent ) :
"""Return a debug representation of a dict or OrderedDict .""" | # pprint represents OrderedDict objects using the tuple init syntax ,
# which is not very readable . Therefore , dictionaries are iterated over .
if _dict is None :
return 'None'
if not isinstance ( _dict , Mapping ) :
raise TypeError ( "Object must be a mapping, but is a %s" % type ( _dict ) )
if isinstance ( ... |
def find_times ( self , site , frametype , gpsstart = None , gpsend = None ) :
"""Query the LDR for times for which frames are avaliable
Use gpsstart and gpsend to restrict the returned times to
this semiopen interval .
@ returns : L { segmentlist < pycbc _ glue . segments . segmentlist > }
@ param site :
... | if gpsstart and gpsend :
url = ( "%s/gwf/%s/%s/segments/%s,%s.json" % ( _url_prefix , site , frametype , gpsstart , gpsend ) )
else :
url = ( "%s/gwf/%s/%s/segments.json" % ( _url_prefix , site , frametype ) )
response = self . _requestresponse ( "GET" , url )
segmentlist = decode ( response . read ( ) )
return... |
def get_diff ( self , commit , other_commit ) :
"""Calculates total additions and deletions
: param commit : First commit
: param other _ commit : Second commit
: return : dictionary : Dictionary with total additions and deletions""" | print ( other_commit , "VS" , commit )
diff = self . repo . git . diff ( commit , other_commit )
return Diff ( diff ) . get_totals ( ) |
def _update_from_pb ( self , app_profile_pb ) :
"""Refresh self from the server - provided protobuf .
Helper for : meth : ` from _ pb ` and : meth : ` reload ` .""" | self . routing_policy_type = None
self . allow_transactional_writes = None
self . cluster_id = None
self . description = app_profile_pb . description
routing_policy_type = None
if app_profile_pb . HasField ( "multi_cluster_routing_use_any" ) :
routing_policy_type = RoutingPolicyType . ANY
self . allow_transacti... |
def render_html ( self , request , instance , context ) :
"""Custom rendering function for HTML output""" | render_template = self . get_render_template ( request , instance , email_format = 'html' )
if not render_template :
return str ( u"{No HTML rendering defined for class '%s'}" % self . __class__ . __name__ )
instance_context = self . get_context ( request , instance , email_format = 'html' , parent_context = contex... |
def routing ( routes , request ) :
"""Definition for route matching : helper""" | # strip trailing slashes from request path
path = request . path . strip ( '/' )
# iterate through routes to match
args = { }
for name , route in routes . items ( ) :
if route [ 'path' ] == '^' : # this section exists because regex doesn ' t work for null character as desired
if path == '' :
mat... |
def diagram_layout ( graph , height = 'freeenergy' , sources = None , targets = None , pos = None , scale = None , center = None , dim = 2 ) :
"""Position nodes such that paths are highlighted , from left to right .
Parameters
graph : ` networkx . Graph ` or ` list ` of nodes
A position will be assigned to ev... | # TODO : private function of packages should not be used .
graph , center = _nx . drawing . layout . _process_params ( graph , center , dim )
num_nodes = len ( graph )
if num_nodes == 0 :
return { }
elif num_nodes == 1 :
return { _nx . utils . arbitrary_element ( graph ) : center }
if sources is None :
sour... |
def execute ( self , input_data ) :
'''Execute method''' | # Spin up the rekall adapter
adapter = RekallAdapter ( )
adapter . set_plugin_name ( self . plugin_name )
rekall_output = adapter . execute ( input_data )
# Process the output data
for line in rekall_output :
if line [ 'type' ] == 'm' : # Meta
self . output [ 'meta' ] = line [ 'data' ]
elif line [ 'type... |
def _assert_input_is_valid ( input_value , # type : Any
validators , # type : List [ InputValidator ]
validated_func , # type : Callable
input_name # type : str
) :
"""Called by the ` validating _ wrapper ` in the first step ( a ) ` apply _ on _ each _ func _ args ` for each function input before
executing the fu... | for validator in validators :
validator . assert_valid ( input_name , input_value ) |
def formatted ( self ) : # pylint : disable = line - too - long
"""Return a human readable string with the statistics for this container .
The operations are sorted by decreasing average time .
The three columns for ` ServerTime ` are included only if the WBEM server
has returned WBEM server response times . ... | # noqa : E501
# pylint : enable = line - too - long
ret = "Statistics (times in seconds, lengths in Bytes):\n"
if self . enabled :
snapshot = sorted ( self . snapshot ( ) , key = lambda item : item [ 1 ] . avg_time , reverse = True )
# Test to see if any server time is non - zero
include_svr = False
for... |
def countBy ( self , val ) :
"""Counts instances of an object that group by a certain criterion . Pass
either a string attribute to count by , or a function that returns the
criterion .""" | def by ( result , key , value ) :
if key not in result :
result [ key ] = 0
result [ key ] += 1
res = self . _group ( self . obj , val , by )
return self . _wrap ( res ) |
def exon_count ( job , job_vars ) :
"""Produces exon counts
job _ vars : tuple Tuple of dictionaries : input _ args and ids""" | input_args , ids = job_vars
work_dir = job . fileStore . getLocalTempDir ( )
uuid = input_args [ 'uuid' ]
sudo = input_args [ 'sudo' ]
# I / O
sort_by_ref , normalize_pl , composite_bed = return_input_paths ( job , work_dir , ids , 'sort_by_ref.bam' , 'normalize.pl' , 'composite_exons.bed' )
# Command
tool = 'jvivian/b... |
def active_qubits ( linear , quadratic ) :
"""Calculate a set of all active qubits . Qubit is " active " if it has
bias or coupling attached .
Args :
linear ( dict [ variable , bias ] / list [ variable , bias ] ) :
Linear terms of the model .
quadratic ( dict [ ( variable , variable ) , bias ] ) :
Quadr... | active = { idx for idx , bias in uniform_iterator ( linear ) }
for edge , _ in six . iteritems ( quadratic ) :
active . update ( edge )
return active |
def _random_subprocessors ( self ) :
"""Produces an iterator of subprocessors . If there are fewer than
self . _ proc _ limit subprocessors to consider ( by knocking out a
minimal subset of working qubits incident to broken couplers ) ,
we work exhaustively . Otherwise , we generate a random set of
` ` self... | if self . _processors is not None :
return ( p for p in self . _processors )
elif 2 ** len ( self . _evil ) <= 8 * self . _proc_limit :
deletions = self . _compute_all_deletions ( )
if len ( deletions ) > self . _proc_limit :
deletions = sample ( deletions , self . _proc_limit )
return ( self . ... |
def Struct ( fields ) : # pylint : disable = invalid - name
"""Construct a struct parameter type description protobuf .
: type fields : list of : class : ` type _ pb2 . StructType . Field `
: param fields : the fields of the struct
: rtype : : class : ` type _ pb2 . Type `
: returns : the appropriate struct... | return type_pb2 . Type ( code = type_pb2 . STRUCT , struct_type = type_pb2 . StructType ( fields = fields ) ) |
def smart_url ( url , obj = None ) :
"""URLs that start with @ are reversed , using the passed in arguments .
Otherwise a straight % substitution is applied .""" | if url . find ( "@" ) >= 0 :
( args , value ) = url . split ( '@' )
if args :
val = getattr ( obj , args , None )
return reverse ( value , args = [ val ] )
else :
return reverse ( value )
else :
if obj is None :
return url
else :
return url % obj . id |
def load_datafile ( name , search_path , codecs = get_codecs ( ) , ** kwargs ) :
"""find datafile and load them from codec
TODO only does the first one
kwargs :
default = if passed will return that on failure instead of throwing""" | return munge . load_datafile ( name , search_path , codecs , ** kwargs ) |
def remove_trunk_ports ( self ) :
"""SDN Controller disable trunk ports
: rtype : list [ tuple [ str , str ] ]""" | ports = self . attributes . get ( "{}Disable Full Trunk Ports" . format ( self . namespace_prefix ) , None )
return self . _parse_ports ( ports = ports ) |
def getgenes ( args ) :
"""% prog getgenes [ - - options ]
Read GenBank file , or retrieve from web .
Output bed , cds files , and pep file ( can turn off with - - nopep ) .
Either - - gb _ dir or - - id / - - simple should be provided .""" | p = OptionParser ( getgenes . __doc__ )
p . add_option ( "--prefix" , default = "gbout" , help = "prefix of output files [default: %default]" )
p . add_option ( "--nopep" , default = False , action = "store_true" , help = "Only get cds and bed, no pep [default: %default]" )
filenames , accessions , idfile , opts , args... |
def decorate ( self , pos , widget , is_first = True ) :
"""builds a list element for given position in the tree .
It consists of the original widget taken from the Tree and some
decoration columns depending on the existence of parent and sibling
positions . The result is a urwid . Columns widget .""" | void = urwid . SolidFill ( ' ' )
line = None
cols = [ ]
depth = self . _tree . depth ( pos )
# add spacer filling all but the last indent
if depth > 0 :
cols . append ( ( depth * self . _indent , void ) ) ,
# spacer
# construct last indent
# TODO
iwidth , icon = self . _construct_collapse_icon ( pos )
available_spa... |
def _read_hopopt_options ( self , length ) :
"""Read HOPOPT options .
Positional arguments :
* length - - int , length of options
Returns :
* dict - - extracted HOPOPT options""" | counter = 0
# length of read options
optkind = list ( )
# option type list
options = dict ( )
# dict of option data
while counter < length : # break when eol triggered
code = self . _read_unpack ( 1 )
if not code :
break
# extract parameter
abbr , desc = _HOPOPT_OPT . get ( code , ( 'none' , 'Un... |
def extract_labels ( filename ) :
"""Extract the labels into a 1D uint8 numpy array [ index ] .""" | with gzip . open ( filename ) as bytestream :
magic = _read32 ( bytestream )
if magic != 2049 :
raise ValueError ( 'Invalid magic number %d in MNIST label file: %s' % ( magic , filename ) )
num_items = _read32 ( bytestream )
buf = bytestream . read ( num_items )
labels = numpy . frombuffer (... |
def proc_info ( pid , attrs = None ) :
'''Return a dictionary of information for a process id ( PID ) .
CLI Example :
. . code - block : : bash
salt ' * ' ps . proc _ info 2322
salt ' * ' ps . proc _ info 2322 attrs = ' [ " pid " , " name " ] '
pid
PID of process to query .
attrs
Optional list of de... | try :
proc = psutil . Process ( pid )
return proc . as_dict ( attrs )
except ( psutil . NoSuchProcess , psutil . AccessDenied , AttributeError ) as exc :
raise CommandExecutionError ( exc ) |
def set_object ( self , obj , properties ) :
"""Add an object to the definition and set its ` ` properties ` ` .""" | self . _objects . add ( obj )
properties = set ( properties )
self . _properties |= properties
pairs = self . _pairs
for p in self . _properties :
if p in properties :
pairs . add ( ( obj , p ) )
else :
pairs . discard ( ( obj , p ) ) |
def run ( self ) :
"""Run parent install , and then save the install dir in the script .""" | install . run ( self )
# Remove old pygubu . py from scripts path if exists
spath = os . path . join ( self . install_scripts , 'pygubu' )
for ext in ( '.py' , '.pyw' ) :
filename = spath + ext
if os . path . exists ( filename ) :
os . remove ( filename )
# Remove old pygubu - designer . bat
if platform... |
def filter_genes ( self , gene_names : Iterable [ str ] , inplace = False ) :
"""Filter the expression matrix against a _ genome ( set of genes ) .
Parameters
gene _ names : list of str
The genome to filter the genes against .
inplace : bool , optional
Whether to perform the operation in - place .
Retur... | return self . drop ( set ( self . genes ) - set ( gene_names ) , inplace = inplace ) |
def mll ( y_true , y_pred , y_var ) :
"""Mean log loss under a Gaussian distribution .
Parameters
y _ true : ndarray
vector of true targets
y _ pred : ndarray
vector of predicted targets
y _ var : float or ndarray
predicted variances
Returns
float :
The mean negative log loss ( negative log like... | return - norm . logpdf ( y_true , loc = y_pred , scale = np . sqrt ( y_var ) ) . mean ( ) |
def makeConstructor ( self , originalConstructor , syntheticMemberList , doesConsumeArguments ) :
""": type syntheticMemberList : list ( SyntheticMember )
: type doesConsumeArguments : bool""" | # Original constructor ' s expected args .
originalConstructorExpectedArgList = [ ]
doesExpectVariadicArgs = False
doesExpectKeywordedArgs = False
if inspect . isfunction ( originalConstructor ) or inspect . ismethod ( originalConstructor ) :
argSpec = inspect . getargspec ( originalConstructor )
# originalCons... |
def update ( self , friendly_name = values . unset , unique_name = values . unset , email = values . unset , cc_emails = values . unset , status = values . unset , verification_code = values . unset , verification_type = values . unset , verification_document_sid = values . unset , extension = values . unset , call_del... | data = values . of ( { 'FriendlyName' : friendly_name , 'UniqueName' : unique_name , 'Email' : email , 'CcEmails' : serialize . map ( cc_emails , lambda e : e ) , 'Status' : status , 'VerificationCode' : verification_code , 'VerificationType' : verification_type , 'VerificationDocumentSid' : verification_document_sid ,... |
def _ffi_module ( self ) :
"""Load the native engine as a python module and register CFFI externs .""" | native_bin_dir = os . path . dirname ( self . binary )
logger . debug ( 'loading native engine python module from: %s' , native_bin_dir )
sys . path . insert ( 0 , native_bin_dir )
return importlib . import_module ( NATIVE_ENGINE_MODULE ) |
def zero_disk ( self , disk_xml = None ) :
"""Collector and publish not zeroed disk metrics""" | troubled_disks = 0
for filer_disk in disk_xml :
raid_state = filer_disk . find ( 'raid-state' ) . text
if not raid_state == 'spare' :
continue
is_zeroed = filer_disk . find ( 'is-zeroed' ) . text
if is_zeroed == 'false' :
troubled_disks += 1
self . push ( 'not_zeroed' , 'disk' , troubled... |
def _verify_support ( identity , ecdh ) :
"""Make sure the device supports given configuration .""" | protocol = identity . identity_dict [ 'proto' ]
if protocol not in { 'ssh' } :
raise NotImplementedError ( 'Unsupported protocol: {}' . format ( protocol ) )
if ecdh :
raise NotImplementedError ( 'No support for ECDH' )
if identity . curve_name not in { formats . CURVE_NIST256 } :
raise NotImplementedError ... |
def new ( sequence_count , start_time , process_id , box_id ) :
"""Make new GlobalID
: param sequence _ count : sequence count
: type sequence _ count : : class : ` int `
: param start _ time : start date time of server ( must be after 2005-01-01)
: type start _ time : : class : ` str ` , : class : ` dateti... | if not isinstance ( start_time , datetime ) :
start_time = datetime . strptime ( start_time , '%Y-%m-%d %H:%M:%S' )
start_time_seconds = int ( ( start_time - datetime ( 2005 , 1 , 1 ) ) . total_seconds ( ) )
return ( box_id << 54 ) | ( process_id << 50 ) | ( start_time_seconds << 20 ) | sequence_count |
def _split_str ( self , field ) :
"""Split title | 7 into ( title , 7)""" | field_items = field . split ( "|" )
if len ( field_items ) == 2 :
return field_items [ 0 ] , field_items [ 1 ]
elif len ( field_items ) == 1 :
return field_items [ 0 ] , None |
def handle_task ( self , uuid_task , worker = None ) :
"""Handle snapshotted event .""" | uuid , task = uuid_task
if task . worker and task . worker . hostname :
worker = self . handle_worker ( ( task . worker . hostname , task . worker ) , )
defaults = { 'name' : task . name , 'args' : task . args , 'kwargs' : task . kwargs , 'eta' : correct_awareness ( maybe_iso8601 ( task . eta ) ) , 'expires' : corr... |
def cdf_discrete ( self , ds , n = None ) :
r'''Computes the cumulative distribution functions for a list of
specified particle diameters .
Parameters
ds : list [ float ]
Particle size diameters , [ m ]
n : int , optional
None ( for the ` order ` specified when the distribution was created ) ,
0 ( num... | return [ self . cdf ( d , n = n ) for d in ds ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.