signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def repr_feature ( feature , max_keys = 100 , indent = 8 , lexigraphic = False ) : '''generate a pretty - printed string for a feature Currently implemented : * StringCounter @ max _ keys : truncate long counters @ indent : indent multi - line displays by this many spaces @ lexigraphic : instead of sortin...
if isinstance ( feature , ( str , bytes ) ) : try : ustr = feature . decode ( 'utf8' ) return ustr except : # failure to decode , not actually utf8 , other binary data return repr ( feature ) if isinstance ( feature , StringCounter ) : return repr_stringcounter ( feature , max_keys ,...
def send_messages ( self , email_messages ) : """Sends one or more EmailMessage objects and returns the number of email messages sent ."""
if not email_messages : return new_conn_created = self . open ( ) if not self . connection : # Failed silently return num_sent = 0 source = settings . AWS_SES_RETURN_PATH for message in email_messages : # SES Configuration sets . If the AWS _ SES _ CONFIGURATION _ SET setting # is not None , append the appropri...
def ilist ( self , in_list = [ ] ) : """Return a list that uses this server ' s IRC casemapping . All strings in this list are lowercased using the server ' s casemapping before inserting them into the list , and the ` ` in ` ` operator takes casemapping into account ."""
new_list = IList ( in_list ) new_list . set_std ( self . features . get ( 'casemapping' ) ) if not self . _casemap_set : self . _imaps . append ( new_list ) return new_list
def update ( self , data , default = False ) : """Update this : attr : ` Config ` with ` ` data ` ` . : param data : must be a ` ` Mapping ` ` like object exposing the ` ` item ` ` method for iterating through key - value pairs . : param default : if ` ` True ` ` the updated : attr : ` settings ` will also ...
for name , value in data . items ( ) : if value is not None : self . set ( name , value , default )
def send ( self , data ) : """Send ` data ` across the data channel to the remote peer ."""
if self . readyState != 'open' : raise InvalidStateError if not isinstance ( data , ( str , bytes ) ) : raise ValueError ( 'Cannot send unsupported data type: %s' % type ( data ) ) self . transport . _data_channel_send ( self , data )
def google_cloud_datastore_delete_expired_sessions ( dormant_for = 86400 , limit = 500 ) : """Deletes expired sessions A session is expired if it expires date is set and has passed or if it has not been accessed for a given period of time . : param dormant _ for : seconds since last access to delete sessions ...
from vishnu . backend . client . google_cloud_datastore import TABLE_NAME from google . cloud import datastore from datetime import datetime from datetime import timedelta now = datetime . utcnow ( ) last_accessed = now - timedelta ( seconds = dormant_for ) client = datastore . Client ( ) accessed_query = client . quer...
def antenna_uvw ( uvw , antenna1 , antenna2 , chunks , nr_of_antenna , check_missing = False , check_decomposition = False , max_err = 100 ) : """Computes per - antenna UVW coordinates from baseline ` ` uvw ` ` , ` ` antenna1 ` ` and ` ` antenna2 ` ` coordinates logically grouped into baseline chunks . The ex...
ant_uvw = _antenna_uvw ( uvw , antenna1 , antenna2 , chunks , nr_of_antenna ) if check_missing : _raise_missing_antenna_errors ( ant_uvw , max_err = max_err ) if check_decomposition : _raise_decomposition_errors ( uvw , antenna1 , antenna2 , chunks , ant_uvw , max_err = max_err ) return ant_uvw
def iter ( self , * , dates = None , start = None , stop = None , step = None , strict = True , ** kwargs ) : """Ephemeris generator based on the data of this one , but with different dates Keyword Arguments : dates ( list of : py : class : ` ~ beyond . dates . date . Date ` ) : Dates from which iterate over ...
# To allow for a loose control of the dates we have to compute # the real starting date of the iterator listeners = kwargs . get ( 'listeners' , [ ] ) if dates : for date in dates : orb = self . propagate ( date ) # Listeners for listen_orb in self . listen ( orb , listeners ) : ...
def repay_funding ( self , amount , currency ) : """Repay funding . Repays the older funding records first . Args : amount ( int ) : Amount of currency to repay currency ( str ) : The currency , example USD Returns : Not specified by cbpro ."""
params = { 'amount' : amount , 'currency' : currency # example : USD } return self . _send_message ( 'post' , '/funding/repay' , data = json . dumps ( params ) )
def validateRegex ( value , regex , flags = 0 , blank = False , strip = None , allowlistRegexes = None , blocklistRegexes = None , excMsg = None ) : """Raises ValidationException if value does not match the regular expression in regex . Returns the value argument . This is similar to calling inputStr ( ) and us...
# Validate parameters . _validateGenericParameters ( blank = blank , strip = strip , allowlistRegexes = allowlistRegexes , blocklistRegexes = blocklistRegexes ) returnNow , value = _prevalidationCheck ( value , blank , strip , allowlistRegexes , blocklistRegexes , excMsg ) if returnNow : return value # Search value...
def _instance_callable ( obj ) : """Given an object , return True if the object is callable . For classes , return True if instances would be callable ."""
if not isinstance ( obj , ClassTypes ) : # already an instance return getattr ( obj , '__call__' , None ) is not None if six . PY3 : # * could * be broken by a class overriding _ _ mro _ _ or _ _ dict _ _ via # a metaclass for base in ( obj , ) + obj . __mro__ : if base . __dict__ . get ( '__call__' ) i...
def find_all_template ( im_source , im_search , threshold = 0.5 , maxcnt = 0 , rgb = False , bgremove = False ) : '''Locate image position with cv2 . templateFind Use pixel match to find pictures . Args : im _ source ( string ) : 图像 、 素材 im _ search ( string ) : 需要查找的图片 threshold : 阈值 , 当相识度小于该阈值的时候 , 就忽略...
# method = cv2 . TM _ CCORR _ NORMED # method = cv2 . TM _ SQDIFF _ NORMED method = cv2 . TM_CCOEFF_NORMED if rgb : s_bgr = cv2 . split ( im_search ) # Blue Green Red i_bgr = cv2 . split ( im_source ) weight = ( 0.3 , 0.3 , 0.4 ) resbgr = [ 0 , 0 , 0 ] for i in range ( 3 ) : # bgr resbgr...
def _open ( self ) : """Bind , use tls"""
try : self . ldap . start_tls_s ( ) # pylint : disable = no - member except ldap . CONNECT_ERROR : # pylint : enable = no - member logging . error ( 'Unable to establish a connection to the LDAP server, ' + 'please check the connection string ' + 'and ensure the remote certificate is signed by a trusted authori...
def mpl_outside_legend ( ax , ** kwargs ) : """Places a legend box outside a matplotlib Axes instance ."""
box = ax . get_position ( ) ax . set_position ( [ box . x0 , box . y0 , box . width * 0.75 , box . height ] ) # Put a legend to the right of the current axis ax . legend ( loc = 'upper left' , bbox_to_anchor = ( 1 , 1 ) , ** kwargs )
def filename_to_task_id ( fname ) : """Map filename to the task id that created it assuming 1k tasks ."""
# This matches the order and size in WikisumBase . out _ filepaths fname = os . path . basename ( fname ) shard_id_increment = { "train" : 0 , "dev" : 800 , "test" : 900 , } parts = fname . split ( "-" ) split = parts [ 1 ] shard_id = parts [ 2 ] task_id = int ( shard_id ) + shard_id_increment [ split ] return task_id
def from_notebook_node ( self , nb , resources = None , ** kw ) : """Uses nbconvert ' s HTMLExporter to generate HTML , with slight modifications . Notes This exporter will only save cells generated with Altair / Vega if they have an SVG image type stored with them . This data is only stored if our fork of ` ...
nb = copy . deepcopy ( nb ) # setup our dictionary that ' s accessible from within jinja templates if resources is None : resources = { "metadata" : { } } elif "metadata" not in resources : resources [ "metadata" ] = { } # iterate over cells in the notebook and transform data as necessary do_not_insert_date = F...
def get_part ( self , vertex_in , vertices_border ) : """List all vertices that are connected to vertex _ in , but are not included in or ' behind ' vertices _ border ."""
vertices_new = set ( self . neighbors [ vertex_in ] ) vertices_part = set ( [ vertex_in ] ) while len ( vertices_new ) > 0 : pivot = vertices_new . pop ( ) if pivot in vertices_border : continue vertices_part . add ( pivot ) pivot_neighbors = set ( self . neighbors [ pivot ] ) pivot_neighbor...
def do_function ( self , prov , func , kwargs ) : '''Perform a function against a cloud provider'''
matches = self . lookup_providers ( prov ) if len ( matches ) > 1 : raise SaltCloudSystemExit ( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}' . format ( prov , ', ' . join ( [ '{0}:{1}' . format ( alias , driver ) for ( alias , driver ) in matches ] ) ) ) alias , driver = matches . pop ( ) ...
def lsst_doc_shortlink_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : """Link to LSST documents given their handle using LSST ' s ls . st link shortener . Example : : : ldm : ` 151 `"""
options = options or { } content = content or [ ] node = nodes . reference ( text = '{0}-{1}' . format ( name . upper ( ) , text ) , refuri = 'https://ls.st/{0}-{1}' . format ( name , text ) , ** options ) return [ node ] , [ ]
def delete_domain ( self , domain_or_name ) : """Delete a SimpleDB domain . . . caution : : This will delete the domain and all items within the domain . : type domain _ or _ name : string or : class : ` boto . sdb . domain . Domain ` object . : param domain _ or _ name : Either the name of a domain or a Doma...
domain , domain_name = self . get_domain_and_name ( domain_or_name ) params = { 'DomainName' : domain_name } return self . get_status ( 'DeleteDomain' , params )
def get_channel_info ( self ) : """Returns a dictionary of channel information key / value pairs ."""
self . assert_open ( ) channel_info = self . handle [ self . global_key + 'channel_id' ] . attrs . items ( ) channel_info = { key : _clean ( value ) for key , value in channel_info } channel_info [ 'channel_number' ] = int ( channel_info [ 'channel_number' ] ) return channel_info
def parse_datetime ( value ) : """Attempts to parse ` value ` into an instance of ` ` datetime . datetime ` ` . If ` value ` is ` ` None ` ` , this function will return ` ` None ` ` . Args : value : A timestamp . This can be a string or datetime . datetime value ."""
if not value : return None elif isinstance ( value , datetime . datetime ) : return value return dateutil . parser . parse ( value )
def magic_plan_b ( filename ) : '''Use this in instances where python - magic is MIA and can ' t be installed for whatever reason'''
cmd = shlex . split ( 'file --mime-type --mime-encoding ' + filename ) stdout , stderr = Popen ( cmd , stdout = PIPE ) . communicate ( ) stdout = stdout . decode ( "utf-8" ) mime_str = stdout . split ( filename + ': ' ) [ 1 ] . strip ( ) return mime_str
def version ( versioninfo = False ) : '''. . versionadded : : 2015.8.0 Returns the version of Git installed on the minion versioninfo : False If ` ` True ` ` , return the version in a versioninfo list ( e . g . ` ` [ 2 , 5, CLI Example : . . code - block : : bash salt myminion git . version'''
contextkey = 'git.version' contextkey_info = 'git.versioninfo' if contextkey not in __context__ : try : version_ = _git_run ( [ 'git' , '--version' ] ) [ 'stdout' ] except CommandExecutionError as exc : log . error ( 'Failed to obtain the git version (error follows):\n%s' , exc ) version...
def grab_names_from_emails ( email_list ) : """Return a dictionary mapping names to email addresses . Only gives a response if the email is found in the staff API / JSON . Expects an API of the format = ' email ' : ' foo @ bar . net ' , ' fullName ' : ' Frank Oo '"""
all_staff = STAFF_LIST emails_names = { } for email in email_list : for person in all_staff : if email == person [ 'email' ] and email not in emails_names : emails_names [ email ] = person [ 'fullName' ] # print emails _ names [ email ] for email in email_list : matched = False ...
def _addAccountRights ( sidObject , user_right ) : '''helper function to add an account right to a user'''
try : if sidObject : _polHandle = win32security . LsaOpenPolicy ( None , win32security . POLICY_ALL_ACCESS ) user_rights_list = [ user_right ] _ret = win32security . LsaAddAccountRights ( _polHandle , sidObject , user_rights_list ) return True # TODO : This needs to be more specific exce...
def _connect_secureish ( * args , ** kwargs ) : """Connect using the safest available options . This turns on encryption ( works in all supported boto versions ) and certificate validation ( in the subset of supported boto versions that can handle certificate validation , namely , those after 2.6.0 ) . Ve...
if tuple ( int ( x ) for x in boto . __version__ . split ( '.' ) ) >= ( 2 , 6 , 0 ) : kwargs [ 'validate_certs' ] = True kwargs [ 'is_secure' ] = True auth_region_name = kwargs . pop ( 'auth_region_name' , None ) conn = connection . S3Connection ( * args , ** kwargs ) if auth_region_name : conn . auth_region_na...
def create_port ( name , network , device_id = None , admin_state_up = True , profile = None ) : '''Creates a new port CLI Example : . . code - block : : bash salt ' * ' neutron . create _ port network - name port - name : param name : Name of port to create : param network : Network name or ID : param ...
conn = _auth ( profile ) return conn . create_port ( name , network , device_id , admin_state_up )
def factoring_qaoa ( n_step , num , minimizer = None , sampler = None , verbose = True ) : """Do the Number partition QAOA . : param num : The number to be factoring . : param n _ step : The number of step of QAOA : param edges : The edges list of the graph . : returns result of QAOA"""
def get_nbit ( n ) : m = 1 while 2 ** m < n : m += 1 return m n1_bits = get_nbit ( int ( num ** 0.5 ) ) - 1 n2_bits = get_nbit ( int ( num ** 0.5 ) ) def mk_expr ( offset , n ) : expr = pauli . Expr . from_number ( 1 ) for i in range ( n ) : expr = expr + 2 ** ( i + 1 ) * q ( i + off...
def unformat_rule ( celf , rule ) : "converts a match rule string from the standard syntax to a dict of { key : value } entries ."
if isinstance ( rule , dict ) : pass elif isinstance ( rule , str ) : PARSE = celf . PARSE parsed = { } chars = iter ( rule ) state = PARSE . EXPECT_NAME curname = None curval = None while True : ch = next ( chars , None ) if ch == None : if state == PARSE . E...
def validate_usage ( self , key_usage , extended_key_usage = None , extended_optional = False ) : """Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified . : param key _ usage : A set of unicode strings of the required key usage purposes ...
self . _validate_path ( ) validate_usage ( self . _context , self . _certificate , key_usage , extended_key_usage , extended_optional ) return self . _path
def write_temp_file ( content ) : """Writes some content into a temporary file and returns it . : param content : The file content : type : string : returns : The temporary file : rtype : file - like object"""
f_temp = NamedTemporaryFile ( delete = True ) f_temp . file . write ( content ) f_temp . file . flush ( ) return f_temp
def read_object_counter ( node_uri , epoch_field , dry_run = False ) : """Reads the object counter for the given epoch / field on the specified node . @ param node _ uri : @ param epoch _ field : @ param dry _ run : @ return : the current object count ."""
return get_property ( node_uri , build_counter_tag ( epoch_field , dry_run ) , ossos_base = True )
def get_markable ( self , markable_id ) : """Returns the markable object for the supplied identifier @ type markable _ id : string @ param markable _ id : term identifier"""
if markable_id in self . idx : return Cmarkable ( self . idx [ markable_id ] , self . type ) else : return None
def pick_sdf ( filename , directory = None ) : """Returns a full path to the chosen SDF file . The supplied file is not expected to contain a recognised SDF extension , this is added automatically . If a file with the extension ` . sdf . gz ` or ` . sdf ` is found the path to it ( excluding the extension ) ...
if directory is None : directory = utils . get_undecorated_calling_module ( ) # If the ' cwd ' is not ' / output ' ( which indicates we ' re in a Container ) # then remove the CWD and the anticipated ' / ' # from the front of the module if os . getcwd ( ) not in [ '/output' ] : directory = d...
def delete ( self ) : """Deletes a folder from the Exchange store . : : folder = service . folder ( ) . get _ folder ( id ) print ( " Deleting folder : % s " % folder . display _ name ) folder . delete ( )"""
if not self . id : raise TypeError ( u"You can't delete a folder that hasn't been created yet." ) body = soap_request . delete_folder ( self ) response_xml = self . service . send ( body ) # noqa # TODO : verify deletion self . _id = None self . _change_key = None return None
def candidates ( self ) : """Generates list of candidates from the DOM ."""
dom = self . dom if dom is None or len ( dom ) == 0 : return None candidates , unlikely_candidates = find_candidates ( dom ) drop_nodes_with_parents ( unlikely_candidates ) return candidates
def get_or_create_user ( self , username , password ) : '''Get or create the given user'''
# Get the groups for this user info = self . get_ad_info ( username , password ) self . debug ( "INFO found: {}" . format ( info ) ) # Find the user try : user = User . objects . get ( username = username ) except User . DoesNotExist : user = User ( username = username ) # Update user user . first_name = info ....
def save ( self ) : """Persist config changes"""
with open ( self . _config_file_path , 'w' ) as file : self . _config_parser . write ( file )
def index_name ( table , columns ) : """Generate an artificial index name ."""
sig = '||' . join ( columns ) key = sha1 ( sig . encode ( 'utf-8' ) ) . hexdigest ( ) [ : 16 ] return 'ix_%s_%s' % ( table , key )
def left_overlaps ( self , other , min_overlap_size = 1 ) : """Does this VariantSequence overlap another on the left side ?"""
if self . alt != other . alt : # allele must match ! return False if len ( other . prefix ) > len ( self . prefix ) : # only consider strings that overlap like : # self : ppppAssss # other : ppAsssss # which excludes cases where the other sequence has a longer # prefix return False elif len ( other . suffix ) <...
def run ( self , data_dir = None ) : """Note : this function will check the experiments directory for a special file , scheduler . info , that details how often each experiment should be run and the last time the experiment was run . If the time since the experiment was run is shorter than the scheduled int...
# XXX : android build needs this . refactor if data_dir : centinel_home = data_dir self . config [ 'dirs' ] [ 'results_dir' ] = os . path . join ( centinel_home , 'results' ) logging . info ( 'Centinel started.' ) if not os . path . exists ( self . config [ 'dirs' ] [ 'results_dir' ] ) : logging . warn ( "C...
def unstructure_attrs_asdict ( self , obj ) : # type : ( Any ) - > Dict [ str , Any ] """Our version of ` attrs . asdict ` , so we can call back to us ."""
attrs = obj . __class__ . __attrs_attrs__ dispatch = self . _unstructure_func . dispatch rv = self . _dict_factory ( ) for a in attrs : name = a . name v = getattr ( obj , name ) rv [ name ] = dispatch ( v . __class__ ) ( v ) return rv
def _show_tables ( self , * args ) : """print the existing tables within the ' doc ' schema"""
v = self . connection . lowest_server_version schema_name = "table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name" table_filter = " AND table_type = 'BASE TABLE'" if v >= TABLE_TYPE_MIN_VERSION else "" self . _exec ( "SELECT format('%s.%s', {schema}, table_name) AS name " "FROM information_schema.tables " "...
def _is_converged ( self , dual_threshold = None , integrality_gap_threshold = None ) : """This method checks the integrality gap to ensure either : * we have found a near to exact solution or * stuck on a local minima . Parameters dual _ threshold : double This sets the minimum width between the dual obj...
# Find the new objective after the message updates new_dual_lp = sum ( [ np . amax ( self . objective [ obj ] . values ) for obj in self . objective ] ) # Update the dual _ gap as the difference between the dual objective of the previous and the current iteration . self . dual_gap = abs ( self . dual_lp - new_dual_lp )...
def find_path_join_using_plus ( node ) : """Finds joining path with plus"""
return ( isinstance ( node , ast . BinOp ) and isinstance ( node . op , ast . Add ) and isinstance ( node . left , ast . BinOp ) and isinstance ( node . left . op , ast . Add ) and isinstance ( node . left . right , ast . Str ) and node . left . right . s in [ '/' , "\\" ] )
def _import_next_layer ( self , proto , length ) : """Import next layer extractor . Positional arguments : * proto - - str , next layer protocol name * length - - int , valid ( not padding ) length Returns : * bool - - flag if extraction of next layer succeeded * Info - - info of next layer * ProtoCha...
if self . _exproto == 'null' and self . _exlayer == 'None' : from pcapkit . protocols . raw import Raw as NextLayer else : from pcapkit . foundation . analysis import analyse as NextLayer # from pcapkit . foundation . analysis import analyse as NextLayer if length == 0 : next_ = NoPayload ( ) elif self . _o...
def _generate_docstring_return_section ( self , return_vals , header , return_element_name , return_element_type , placeholder , indent ) : """Generate the Returns section of a function / method docstring ."""
# If all return values are None , return none non_none_vals = [ return_val for return_val in return_vals if return_val and return_val != 'None' ] if not non_none_vals : return header + indent + 'None.' # Get only values with matching brackets that can be cleaned up non_none_vals = [ return_val . strip ( ' ()\t\n' )...
def accounts_balances ( self , accounts ) : """Returns how many RAW is owned and how many have not yet been received by * * accounts * * list : param accounts : list of accounts to return balances for : type accounts : list of str : raises : : py : exc : ` nano . rpc . RPCException ` > > > rpc . accounts ...
accounts = self . _process_value ( accounts , 'list' ) payload = { "accounts" : accounts } resp = self . call ( 'accounts_balances' , payload ) accounts_balances = resp . get ( 'balances' ) or { } for account , balances in accounts_balances . items ( ) : for k in balances : balances [ k ] = int ( balances [...
def getSamplingWorkflowEnabled ( self ) : """Returns True if the sample of this Analysis Request has to be collected by the laboratory personnel"""
template = self . getTemplate ( ) if template : return template . getSamplingRequired ( ) return self . bika_setup . getSamplingWorkflowEnabled ( )
def to_json ( self ) : """Returns an input shard state for the remaining inputs . Returns : A json - izable version of the remaining InputReader ."""
result = super ( _ReducerReader , self ) . to_json ( ) result [ "current_key" ] = self . encode_data ( self . current_key ) result [ "current_values" ] = self . encode_data ( self . current_values ) return result
def get_json ( environ ) : '''Return the request body as JSON'''
content_type = environ . get ( 'CONTENT_TYPE' , '' ) if content_type != 'application/json' : raise HTTPError ( 406 , 'JSON required' ) try : return salt . utils . json . loads ( read_body ( environ ) ) except ValueError as exc : raise HTTPError ( 400 , exc )
def add_phase ( self ) : """Context manager for when adding all the tokens"""
# add stuff yield self # Make sure we output eveything self . finish_hanging ( ) # Remove trailing indents and dedents while len ( self . result ) > 1 and self . result [ - 2 ] [ 0 ] in ( INDENT , ERRORTOKEN , NEWLINE ) : self . result . pop ( - 2 )
def fetch_token ( self , ** kwargs ) : """Fetch a new token using the supplied code . : param str code : A previously obtained auth code ."""
if 'client_secret' not in kwargs : kwargs . update ( client_secret = self . client_secret ) return self . session . fetch_token ( token_url , ** kwargs )
def get_tracks_from_album ( album_name ) : '''Gets tracks from an album using Spotify ' s API'''
spotify = spotipy . Spotify ( ) album = spotify . search ( q = 'album:' + album_name , limit = 1 ) album_id = album [ 'tracks' ] [ 'items' ] [ 0 ] [ 'album' ] [ 'id' ] results = spotify . album_tracks ( album_id = str ( album_id ) ) songs = [ ] for items in results [ 'items' ] : songs . append ( items [ 'name' ] ) ...
def update ( self , * args , ** kwargs ) : """update ( ) method will * recursively * update nested dict : > > > d = Dict ( { ' a ' : { ' b ' : { ' c ' : 3 , ' d ' : 4 } , ' h ' : 4 } } ) > > > d . update ( { ' a ' : { ' b ' : { ' c ' : ' 888 ' } } } ) { ' a ' : { ' b ' : { ' c ' : ' 888 ' , ' d ' : 4 } , ' h ...
for arg in args : if not arg : continue elif isinstance ( arg , dict ) : for k , v in arg . items ( ) : self . _update_kv ( k , v ) elif isinstance ( arg , ( list , tuple ) ) and ( not isinstance ( arg [ 0 ] , ( list , tuple ) ) ) : k = arg [ 0 ] v = arg [ 1 ] ...
def baseline ( y_true , y_score = None ) : """Number of positive labels divided by number of labels , or zero if there are no labels"""
if len ( y_true ) > 0 : return np . nansum ( y_true ) / count ( y_true , countna = False ) else : return 0.0
def printClassTree ( self , element = None , showids = False , labels = False , showtype = False ) : """Print nicely into stdout the class tree of an ontology Note : indentation is made so that ids up to 3 digits fit in , plus a space . [123]1 - - [1]123 - - [12]12 - -"""
TYPE_MARGIN = 11 # length for owl : class etc . . if not element : # first time for x in self . toplayer_classes : printGenericTree ( x , 0 , showids , labels , showtype , TYPE_MARGIN ) else : printGenericTree ( element , 0 , showids , labels , showtype , TYPE_MARGIN )
def get_setter ( cls , prop_name , # @ NoSelf user_setter = None , setter_takes_name = False , user_getter = None , getter_takes_name = False ) : """The setter follows the rules of the getter . First search for property variable , then logical custom setter . If no setter is found , None is returned ( i . e . t...
has_prop_variable = cls . has_prop_attribute ( prop_name ) # WARNING ! These are deprecated has_specific_setter = hasattr ( cls , SET_PROP_NAME % { 'prop_name' : prop_name } ) has_general_setter = hasattr ( cls , SET_GENERIC_NAME ) if not ( has_prop_variable or has_specific_setter or has_general_setter or user_setter )...
def rooms ( request , template = "rooms.html" ) : """Homepage - lists all rooms ."""
context = { "rooms" : ChatRoom . objects . all ( ) } return render ( request , template , context )
def make_table ( data , col_names ) : """Code for this RST - formatted table generator comes from http : / / stackoverflow . com / a / 11350643"""
n_cols = len ( data [ 0 ] ) assert n_cols == len ( col_names ) col_sizes = [ max ( len ( r [ i ] ) for r in data ) for i in range ( n_cols ) ] for i , cname in enumerate ( col_names ) : if col_sizes [ i ] < len ( cname ) : col_sizes [ i ] = len ( cname ) formatter = ' ' . join ( '{:<%d}' % c for c in col_si...
def read_wavefront ( fname_obj ) : """Returns mesh dictionary along with their material dictionary from a wavefront ( . obj and / or . mtl ) file ."""
fname_mtl = '' geoms = read_objfile ( fname_obj ) for line in open ( fname_obj ) : if line : split_line = line . strip ( ) . split ( ' ' , 1 ) if len ( split_line ) < 2 : continue prefix , data = split_line [ 0 ] , split_line [ 1 ] if 'mtllib' in prefix : fnam...
def _find_script ( script_name ) : """Find the script . If the input is not a file , then $ PATH will be searched ."""
if os . path . isfile ( script_name ) : return script_name path = os . getenv ( 'PATH' , os . defpath ) . split ( os . pathsep ) for dir in path : if dir == '' : continue fn = os . path . join ( dir , script_name ) if os . path . isfile ( fn ) : return fn print >> sys . stderr , 'Could n...
def or_filter ( self , filter_or_string , * args , ** kwargs ) : """Adds a list of : class : ` ~ es _ fluent . filters . core . Or ` clauses , automatically generating the an : class : ` ~ es _ fluent . filters . core . Or ` filter if it does not exist ."""
or_filter = self . find_filter ( Or ) if or_filter is None : or_filter = Or ( ) self . filters . append ( or_filter ) or_filter . add_filter ( build_filter ( filter_or_string , * args , ** kwargs ) ) return or_filter
def export ( self , name , columns , points ) : """Write the points in MQTT ."""
WHITELIST = '_-' + string . ascii_letters + string . digits SUBSTITUTE = '_' def whitelisted ( s , whitelist = WHITELIST , substitute = SUBSTITUTE ) : return '' . join ( c if c in whitelist else substitute for c in s ) for sensor , value in zip ( columns , points ) : try : sensor = [ whitelisted ( name ...
def run_graphviz ( program , code , options = [ ] , format = 'png' ) : """Runs graphviz programs and returns image data Copied from https : / / github . com / tkf / ipython - hierarchymagic / blob / master / hierarchymagic . py"""
import os from subprocess import Popen , PIPE dot_args = [ program ] + options + [ '-T' , format ] if os . name == 'nt' : # Avoid opening shell window . # * https : / / github . com / tkf / ipython - hierarchymagic / issues / 1 # * http : / / stackoverflow . com / a / 2935727/727827 p = Popen ( dot_args , stdout = ...
def _expand_json ( self , j ) : """Decompress the BLOB portion of the usernotes . Arguments : j : the JSON returned from the wiki page ( dict ) Returns a Dict with the ' blob ' key removed and a ' users ' key added"""
decompressed_json = copy . copy ( j ) decompressed_json . pop ( 'blob' , None ) # Remove BLOB portion of JSON # Decode and decompress JSON compressed_data = base64 . b64decode ( j [ 'blob' ] ) original_json = zlib . decompress ( compressed_data ) . decode ( 'utf-8' ) decompressed_json [ 'users' ] = json . loads ( origi...
def framesToFrameRange ( frames , sort = True , zfill = 0 , compress = False ) : """Converts an iterator of frames into a frame range string . Args : frames ( collections . Iterable ) : sequence of frames to process sort ( bool ) : sort the sequence before processing zfill ( int ) : width for zero padding...
if compress : frames = unique ( set ( ) , frames ) frames = list ( frames ) if not frames : return '' if len ( frames ) == 1 : return pad ( frames [ 0 ] , zfill ) if sort : frames . sort ( ) return ',' . join ( FrameSet . framesToFrameRanges ( frames , zfill ) )
def gettempdir ( ) : """Accessor for tempfile . tempdir ."""
global tempdir if tempdir is None : _once_lock . acquire ( ) try : if tempdir is None : tempdir = _get_default_tempdir ( ) finally : _once_lock . release ( ) return tempdir
def fix_config ( self , options ) : """Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary . : param options : the options to fix : type options : dict : return : the ( potentially ) fixed options : rtype : dict"""
options = super ( ClassSelector , self ) . fix_config ( options ) opt = "index" if opt not in options : options [ opt ] = "last" if opt not in self . help : self . help [ opt ] = "The class index (1-based number); 'first' and 'last' are accepted as well (string)." opt = "unset" if opt not in options : optio...
def grid_distortion ( img , num_steps = 10 , xsteps = [ ] , ysteps = [ ] , interpolation = cv2 . INTER_LINEAR , border_mode = cv2 . BORDER_REFLECT_101 , value = None ) : """Reference : http : / / pythology . blogspot . sg / 2014/03 / interpolation - on - regular - distorted - grid . html"""
height , width = img . shape [ : 2 ] x_step = width // num_steps xx = np . zeros ( width , np . float32 ) prev = 0 for idx , x in enumerate ( range ( 0 , width , x_step ) ) : start = x end = x + x_step if end > width : end = width cur = width else : cur = prev + x_step * xsteps [...
def create_snapshot ( self , name ) : """POST / : login / machines / : id / snapshots : param name : identifier for snapshot : type name : : py : class : ` basestring ` : rtype : : py : class : ` smartdc . machine . Snapshot ` Create a snapshot for this machine ' s current state with the given ` name ` ."...
params = { 'name' : name } j , _ = self . datacenter . request ( 'POST' , self . path + '/snapshots' , data = params ) return Snapshot ( machine = self , data = j , name = name )
def simulate_phases ( self , phase_map : Dict [ Tuple [ int , ... ] , float ] ) : """Simulate a set of phase gates on the xmon architecture . Args : phase _ map : A map from a tuple of indices to a value , one for each phase gate being simulated . If the tuple key has one index , then this is a Z phase gate...
self . _pool . map ( _clear_scratch , self . _shard_num_args ( ) ) # Iterate over the map of phase data . for indices , half_turns in phase_map . items ( ) : args = self . _shard_num_args ( { 'indices' : indices , 'half_turns' : half_turns } ) if len ( indices ) == 1 : self . _pool . map ( _single_qubit...
def tolist ( self ) : """The fastest way to convert the vector into a python list ."""
the_list = [ ] self . _fill_list ( self . _root , self . _shift , the_list ) the_list . extend ( self . _tail ) return the_list
def get ( self ) : """Flushes the call _ queue and returns the data . Note : Since this object is a simple wrapper , just return the data . Returns : The object that was ` put ` ."""
if self . call_queue : return self . apply ( lambda df : df ) . data else : return self . data . copy ( )
def get_selected_terms ( term_doc_matrix , scores , num_term_to_keep = None ) : '''Parameters term _ doc _ matrix : TermDocMatrix or descendant scores : array - like Same length as number of terms in TermDocMatrix . num _ term _ to _ keep : int , default = 4000. Should be > 0 . Number of terms to keep . W...
num_term_to_keep = AutoTermSelector . _add_default_num_terms_to_keep ( num_term_to_keep ) term_doc_freq = term_doc_matrix . get_term_freq_df ( ) term_doc_freq [ 'count' ] = term_doc_freq . sum ( axis = 1 ) term_doc_freq [ 'score' ] = scores score_terms = AutoTermSelector . _get_score_terms ( num_term_to_keep , term_doc...
def _get_block_publisher ( self , state_hash ) : """Returns the block publisher based on the consensus module set by the " sawtooth _ settings " transaction family . Args : state _ hash ( str ) : The current state root hash for reading settings . Raises : InvalidGenesisStateError : if any errors occur get...
state_view = self . _state_view_factory . create_view ( state_hash ) try : class BatchPublisher : def send ( self , transactions ) : # Consensus implementations are expected to have handling # in place for genesis operation . This should includes # adding any authorization and registrations ...
def _get_table_info ( self ) : """Database - specific method to get field names"""
self . rowid = None self . fields = [ ] self . field_info = { } self . cursor . execute ( 'DESCRIBE %s' % self . name ) for row in self . cursor . fetchall ( ) : field , typ , null , key , default , extra = row self . fields . append ( field ) self . field_info [ field ] = { 'type' : typ , 'NOT NULL' : null...
def get ( self , path , params = None ) : """Perform GET request"""
r = requests . get ( url = self . url + path , params = params , timeout = self . timeout ) r . raise_for_status ( ) return r . json ( )
def _at_warn ( self , calculator , rule , scope , block ) : """Implements @ warn"""
value = calculator . calculate ( block . argument ) log . warn ( repr ( value ) )
def review_metadata_csv ( filedir , input_filepath ) : """Check validity of metadata fields . : param filedir : This field is the filepath of the directory whose csv has to be made . : param outputfilepath : This field is the file path of the output csv . : param max _ bytes : This field is the maximum file...
try : metadata = load_metadata_csv ( input_filepath ) except ValueError as e : print_error ( e ) return False with open ( input_filepath ) as f : csv_in = csv . reader ( f ) header = next ( csv_in ) n_headers = len ( header ) if header [ 0 ] == 'filename' : res = review_metadata_csv_...
def if_else ( self , pred , likely = None ) : """A context manager which sets up two conditional basic blocks based on the given predicate ( a i1 value ) . A tuple of context managers is yield ' ed . Each context manager acts as a if _ then ( ) block . * likely * has the same meaning as in if _ then ( ) . ...
bb = self . basic_block bbif = self . append_basic_block ( name = _label_suffix ( bb . name , '.if' ) ) bbelse = self . append_basic_block ( name = _label_suffix ( bb . name , '.else' ) ) bbend = self . append_basic_block ( name = _label_suffix ( bb . name , '.endif' ) ) br = self . cbranch ( pred , bbif , bbelse ) if ...
def resource_reaches_status ( self , resource , resource_id , expected_stat = 'available' , msg = 'resource' , max_wait = 120 ) : """Wait for an openstack resources status to reach an expected status within a specified time . Useful to confirm that nova instances , cinder vols , snapshots , glance images , heat...
tries = 0 resource_stat = resource . get ( resource_id ) . status while resource_stat != expected_stat and tries < ( max_wait / 4 ) : self . log . debug ( '{} status check: ' '{} [{}:{}] {}' . format ( msg , tries , resource_stat , expected_stat , resource_id ) ) time . sleep ( 4 ) resource_stat = resource ...
def to_wgs84 ( east , north , crs ) : """Convert any CRS with ( east , north ) coordinates to WGS84 : param east : east coordinate : type east : float : param north : north coordinate : type north : float : param crs : CRS enum constants : type crs : constants . CRS : return : latitude and longitude c...
return transform_point ( ( east , north ) , crs , CRS . WGS84 )
def add_line ( preso , x1 , y1 , x2 , y2 , width = "3pt" , color = "red" ) : """Arrow pointing up to right : context . xml : office : automatic - styles / < style : style style : name = " gr1 " style : family = " graphic " style : parent - style - name = " objectwithoutfill " > < style : graphic - propertie...
marker_end_ratio = .459 / 3 # .459cm / 3pt marker_start_ratio = .359 / 3 # .359cm / 3pt stroke_ratio = .106 / 3 # .106cm / 3pt w = float ( width [ 0 : width . index ( "pt" ) ] ) sw = w * stroke_ratio mew = w * marker_end_ratio msw = w * marker_start_ratio attribs = { "svg:stroke-width" : "{}cm" . format ( sw ) , "svg:s...
def collect_usage_pieces ( self , ctx ) : """Prepend " [ - - ] " before " [ ARGV ] . . . " ."""
pieces = super ( ProfilingCommand , self ) . collect_usage_pieces ( ctx ) assert pieces [ - 1 ] == '[ARGV]...' pieces . insert ( - 1 , 'SCRIPT' ) pieces . insert ( - 1 , '[--]' ) return pieces
def find_mode ( data ) : """Returns the appropriate QR Code mode ( an integer constant ) for the provided ` data ` . : param bytes data : Data to check . : rtype : int"""
if data . isdigit ( ) : return consts . MODE_NUMERIC if is_alphanumeric ( data ) : return consts . MODE_ALPHANUMERIC if is_kanji ( data ) : return consts . MODE_KANJI return consts . MODE_BYTE
def _attr_display ( value , html_element ) : '''Set the display value'''
if value == 'block' : html_element . display = Display . block elif value == 'none' : html_element . display = Display . none else : html_element . display = Display . inline
def field_singleton_schema ( # noqa : C901 ( ignore complexity ) field : Field , * , by_alias : bool , model_name_map : Dict [ Type [ 'main.BaseModel' ] , str ] , schema_overrides : bool = False , ref_prefix : Optional [ str ] = None , ) -> Tuple [ Dict [ str , Any ] , Dict [ str , Any ] ] : """This function is ind...
ref_prefix = ref_prefix or default_prefix definitions : Dict [ str , Any ] = { } if field . sub_fields : return field_singleton_sub_fields_schema ( field . sub_fields , by_alias = by_alias , model_name_map = model_name_map , schema_overrides = schema_overrides , ref_prefix = ref_prefix , ) if field . type_ is Any :...
async def grab ( self , * , countries = None , limit = 0 ) : """Gather proxies from the providers without checking . : param list countries : ( optional ) List of ISO country codes where should be located proxies : param int limit : ( optional ) The maximum number of proxies : ref : ` Example of usage < pro...
self . _countries = countries self . _limit = limit task = asyncio . ensure_future ( self . _grab ( check = False ) ) self . _all_tasks . append ( task )
def updatepLvlNextFunc ( self ) : '''A method that creates the pLvlNextFunc attribute as a sequence of linear functions , indicating constant expected permanent income growth across permanent income levels . Draws on the attribute PermGroFac , and installs a special retirement function when it exists . Para...
orig_time = self . time_flow self . timeFwd ( ) pLvlNextFunc = [ ] for t in range ( self . T_cycle ) : pLvlNextFunc . append ( LinearInterp ( np . array ( [ 0. , 1. ] ) , np . array ( [ 0. , self . PermGroFac [ t ] ] ) ) ) self . pLvlNextFunc = pLvlNextFunc self . addToTimeVary ( 'pLvlNextFunc' ) if not orig_time :...
def main_callback ( self , * args , ** kwargs ) : """Main callback called when an event is received from an entry point . : returns : The entry point ' s callback . : rtype : function : raises NotImplementedError : When the entrypoint doesn ' t have the required attributes ."""
if not self . callback : raise NotImplementedError ( 'Entrypoints must declare `callback`' ) if not self . settings : raise NotImplementedError ( 'Entrypoints must declare `settings`' ) self . callback . im_self . db = None # 1 . Start all the middlewares with self . debug ( * args , ** kwargs ) : with self...
def bundle ( context , name ) : """Add a new bundle ."""
if context . obj [ 'db' ] . bundle ( name ) : click . echo ( click . style ( 'bundle name already exists' , fg = 'yellow' ) ) context . abort ( ) new_bundle = context . obj [ 'db' ] . new_bundle ( name ) context . obj [ 'db' ] . add_commit ( new_bundle ) # add default version new_version = context . obj [ 'db' ...
def create ( self , sid ) : """Create a new ShortCodeInstance : param unicode sid : The SID of a Twilio ShortCode resource : returns : Newly created ShortCodeInstance : rtype : twilio . rest . proxy . v1 . service . short _ code . ShortCodeInstance"""
data = values . of ( { 'Sid' : sid , } ) payload = self . _version . create ( 'POST' , self . _uri , data = data , ) return ShortCodeInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , )
def wait_ready ( self , name , timeout = 5.0 , sleep_interval = 0.2 ) : """Wait for a newly created bucket to be ready . : param string name : the name to wait for : param seconds timeout : the maximum amount of time to wait : param seconds sleep _ interval : the number of time to sleep between each probe ...
end = time ( ) + timeout while True : try : info = self . bucket_info ( name ) . value for node in info [ 'nodes' ] : if node [ 'status' ] != 'healthy' : raise NotReadyError . pyexc ( 'Not all nodes are healthy' ) return # No error and all OK except E ...
def handle ( client_message , handle_event_partition_lost = None , to_object = None ) : """Event handler"""
message_type = client_message . get_message_type ( ) if message_type == EVENT_PARTITIONLOST and handle_event_partition_lost is not None : partition_id = client_message . read_int ( ) lost_backup_count = client_message . read_int ( ) source = None if not client_message . read_bool ( ) : source = ...
def rr_history ( self , query , query_type = "A" ) : '''Get the RR ( Resource Record ) History of the given domain or IP . The default query type is for ' A ' records , but the following query types are supported : A , NS , MX , TXT , CNAME For details , see https : / / investigate . umbrella . com / docs /...
if query_type not in Investigate . SUPPORTED_DNS_TYPES : raise Investigate . UNSUPPORTED_DNS_QUERY # if this is an IP address , query the IP if Investigate . IP_PATTERN . match ( query ) : return self . _ip_rr_history ( query , query_type ) # otherwise , query the domain return self . _domain_rr_history ( query...
def read_spec ( filename , fname = '' , ** kwargs ) : """Read FITS or ASCII spectrum . Parameters filename : str or file pointer Spectrum file name or pointer . fname : str Filename . This is * only * used if ` ` filename ` ` is a pointer . kwargs : dict Keywords acceptable by : func : ` read _ fits _...
if isinstance ( filename , str ) : fname = filename elif not fname : # pragma : no cover raise exceptions . SynphotError ( 'Cannot determine filename.' ) if fname . endswith ( 'fits' ) or fname . endswith ( 'fit' ) : read_func = read_fits_spec else : read_func = read_ascii_spec return read_func ( filena...
def list_container_objects ( container_name , profile , ** libcloud_kwargs ) : '''List container objects ( e . g . files ) for the given container _ id on the given profile : param container _ name : Container name : type container _ name : ` ` str ` ` : param profile : The profile key : type profile : ` ` ...
conn = _get_driver ( profile = profile ) container = conn . get_container ( container_name ) libcloud_kwargs = salt . utils . args . clean_kwargs ( ** libcloud_kwargs ) objects = conn . list_container_objects ( container , ** libcloud_kwargs ) ret = [ ] for obj in objects : ret . append ( { 'name' : obj . name , 's...
def to_output ( data ) : """Convert WA - KAT frontend dataset to three output datasets - ` MRC ` , ` MARC ` and ` Dublin core ` . Conversion is implemented as filling ofthe MRC template , which is then converted to MARC record . Dublin core is converted standalone from the input dataset ."""
data = json . loads ( data ) # postprocessing if "keywords" in data : mdt , cz_keywords , en_keywords = compile_keywords ( data [ "keywords" ] ) del data [ "keywords" ] data [ "mdt" ] = mdt data [ "cz_keywords" ] = cz_keywords data [ "en_keywords" ] = en_keywords data [ "annotation" ] = data [ "anno...