signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def symmetrify ( A , upper = False ) : """Take the square matrix A and make it symmetrical by copting elements from the lower half to the upper works IN PLACE . note : tries to use cython , falls back to a slower numpy version"""
if use_linalg_cython : _symmetrify_cython ( A , upper ) else : _symmetrify_numpy ( A , upper )
def _writeString ( self , obj , use_reference = True ) : """Appends a string to the serialization stream : param obj : String to serialize : param use _ reference : If True , allow writing a reference"""
# TODO : Convert to " modified UTF - 8" # http : / / docs . oracle . com / javase / 7 / docs / api / java / io / DataInput . html # modified - utf - 8 string = to_bytes ( obj , "utf-8" ) if use_reference and isinstance ( obj , JavaString ) : try : idx = self . references . index ( obj ) except ValueErro...
def fnmatch_pathname_to_regex ( pattern ) : """Implements fnmatch style - behavior , as though with FNM _ PATHNAME flagged ; the path seperator will not match shell - style ' * ' and ' . ' wildcards ."""
i , n = 0 , len ( pattern ) nonsep = '' . join ( [ '[^' , os . sep , ']' ] ) res = [ ] while i < n : c = pattern [ i ] i = i + 1 if c == '*' : try : if pattern [ i ] == '*' : i = i + 1 res . append ( '.*' ) if pattern [ i ] == '/' : ...
def installShlibLinks ( dest , source , env ) : """If we are installing a versioned shared library create the required links ."""
Verbose = False symlinks = listShlibLinksToInstall ( dest , source , env ) if Verbose : print ( 'installShlibLinks: symlinks={:r}' . format ( SCons . Tool . StringizeLibSymlinks ( symlinks ) ) ) if symlinks : SCons . Tool . CreateLibSymlinks ( env , symlinks ) return
def _ensure_opened ( self ) : """Start monitors , or restart after a fork . Hold the lock when calling this ."""
if not self . _opened : self . _opened = True self . _update_servers ( ) # Start or restart the events publishing thread . if self . _publish_tp or self . _publish_server : self . __events_executor . open ( ) # Ensure that the monitors are open . for server in itervalues ( self . _servers ) : ...
def makeQ ( r1 , r2 , r3 , r4 = 0 ) : """matrix involved in quaternion rotation"""
Q = np . asarray ( [ [ r4 , - r3 , r2 , r1 ] , [ r3 , r4 , - r1 , r2 ] , [ - r2 , r1 , r4 , r3 ] , [ - r1 , - r2 , - r3 , r4 ] ] ) return Q
def comment ( self , format , * args ) : """Add a comment to hash table before saving to disk . You can add as many comment lines as you like . These comment lines are discarded when loading the file . If you use a null format , all comments are deleted ."""
return lib . zhashx_comment ( self . _as_parameter_ , format , * args )
def refine_MIDDLEWARE_CLASSES ( original ) : """Django docs say that the LocaleMiddleware should come after the SessionMiddleware . Here , we make sure that the SessionMiddleware is enabled and then place the LocaleMiddleware at the correct position . Be careful with the order when refining the MiddlewareClas...
try : session_middleware_index = original . index ( 'django.contrib.sessions.middleware.SessionMiddleware' ) original . insert ( session_middleware_index + 1 , 'django.middleware.locale.LocaleMiddleware' ) return original except ValueError : raise LookupError ( 'SessionMiddleware not found! Please make ...
def nvp2pl ( normal , point ) : """Make a plane from a normal vector and a point . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / nvp2pl _ c . html : param normal : A normal vector defining a plane . : type normal : 3 - Element Array of floats : param point : A point definin...
normal = stypes . toDoubleVector ( normal ) point = stypes . toDoubleVector ( point ) plane = stypes . Plane ( ) libspice . nvp2pl_c ( normal , point , ctypes . byref ( plane ) ) return plane
def _prefix_from_ip_int ( self , ip_int ) : """Return prefix length from the bitwise netmask . Args : ip _ int : An integer , the netmask in expanded bitwise format Returns : An integer , the prefix length . Raises : ValueError : If the input intermingles zeroes & ones"""
trailing_zeroes = _count_righthand_zero_bits ( ip_int , self . _max_prefixlen ) prefixlen = self . _max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = ( 1 << prefixlen ) - 1 if leading_ones != all_ones : byteslen = self . _max_prefixlen // 8 details = _int_to_bytes ( ip_int , by...
def cublasZhpr2 ( handle , uplo , n , alpha , x , inx , y , incy , AP ) : """Rank - 2 operation on Hermitian - packed matrix ."""
status = _libcublas . cublasZhpr2_v2 ( handle , _CUBLAS_FILL_MODE [ uplo ] , n , ctypes . byref ( cuda . cuDoubleComplex ( alpha . real , alpha . imag ) ) , int ( x ) , incx , int ( y ) , incy , int ( AP ) ) cublasCheckStatus ( status )
def evrs ( self ) : """Getter EVRs dictionary"""
if self . _evrs is None : import ait . core . evr as evr self . _evrs = evr . getDefaultDict ( ) return self . _evrs
def simple_tpl_from_pars ( parnames , tplfilename = 'model.input.tpl' ) : """Make a template file just assuming a list of parameter names the values of which should be listed in order in a model input file Args : parnames : list of names from which to make a template file tplfilename : filename for TPL file...
with open ( tplfilename , 'w' ) as ofp : ofp . write ( 'ptf ~\n' ) [ ofp . write ( '~{0:^12}~\n' . format ( cname ) ) for cname in parnames ]
def normalizeCoordinateTuple ( value ) : """Normalizes coordinate tuple . * * * value * * must be a ` ` tuple ` ` or ` ` list ` ` . * * * value * * must have exactly two items . * * * value * * items must be an : ref : ` type - int - float ` . * Returned value is a ` ` tuple ` ` of two values of the same ty...
if not isinstance ( value , ( tuple , list ) ) : raise TypeError ( "Coordinates must be tuple instances, not %s." % type ( value ) . __name__ ) if len ( value ) != 2 : raise ValueError ( "Coordinates must be tuples containing two items, " "not %d." % len ( value ) ) x , y = value x = normalizeX ( x ) y = normal...
def get_secret ( self , handle , contributor ) : """Retrieve an existing secret ' s value . : param handle : Secret handle : param contributor : User instance to perform contributor validation , which means that only secrets for the given contributor will be looked up ."""
queryset = self . all ( ) if contributor is not None : queryset = queryset . filter ( contributor = contributor ) secret = queryset . get ( handle = handle ) return secret . value
def update_hosts_file ( ip , entry ) : """Updates the / etc / hosts file for the specified ip This method updates the / etc / hosts file for the specified IP address with the specified entry . : param ip : ( str ) IP address to be added or updated : param entry : ( str ) Hosts file entry to be added : ret...
log = logging . getLogger ( mod_logger + '.update_hosts_file' ) # Validate args if not isinstance ( ip , basestring ) : msg = 'ip argument must be a string' log . error ( msg ) raise CommandError ( msg ) if not isinstance ( entry , basestring ) : msg = 'entry argument must be a string' log . error (...
def add ( self , directory , path = None ) -> None : """Add a directory and optionally its path ."""
objecttools . valid_variable_identifier ( directory ) if path is None : path = directory setattr ( self , directory , path )
def delete_all_events ( self , calendar_ids = ( ) ) : """Deletes all events managed through Cronofy from the all of the user ' s calendars . : param tuple calendar _ ids : List of calendar ids to delete events for . ( Optional . Default empty tuple )"""
params = { 'delete_all' : True } if calendar_ids : params = { 'calendar_ids[]' : calendar_ids } self . request_handler . delete ( endpoint = 'events' , params = params )
def _get_anns_to_remove ( in_file ) : """Find larger annotations , if present in VCF , that slow down processing ."""
to_remove = [ "ANN" , "LOF" ] to_remove_str = tuple ( [ "##INFO=<ID=%s" % x for x in to_remove ] ) cur_remove = [ ] with utils . open_gzipsafe ( in_file ) as in_handle : for line in in_handle : if not line . startswith ( "#" ) : break elif line . startswith ( to_remove_str ) : ...
def add_execution_data ( self , context_id , data ) : """Within a context , append data to the execution result . Args : context _ id ( str ) : the context id returned by create _ context data ( bytes ) : data to append Returns : ( bool ) : True if the operation is successful , False if the context _ id...
if context_id not in self . _contexts : LOGGER . warning ( "Context_id not in contexts, %s" , context_id ) return False context = self . _contexts . get ( context_id ) context . add_execution_data ( data ) return True
def partition ( pred , iterable ) : """Partition an iterable . Arguments pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns A two - tuple of lists with the first list containing the elements on whic...
pos , neg = [ ] , [ ] pos_append , neg_append = pos . append , neg . append for elem in iterable : if pred ( elem ) : pos_append ( elem ) else : neg_append ( elem ) return neg , pos
def upload ( self , url = None , filepath = None , multipart = True , params = None , upload_processes = None , intelligent = False ) : """Uploads a file either through a local filepath or external _ url . Uses multipart by default and Intelligent Ingestion by default ( if enabled ) . You can specify the number...
if params : # Check the structure of parameters STORE_SCHEMA . check ( params ) if filepath and url : # Raise an error for using both filepath and external url raise ValueError ( "Cannot upload file and external url at the same time" ) if filepath : # Uploading from local drive if intelligent : resp...
def _connectToFB ( self ) : """Establish the actual TCP connection to FB"""
if self . connected_to_fb : logger . debug ( "Already connected to fb" ) return True logger . debug ( "Connecting to fb" ) token = facebook_login . get_fb_token ( ) try : self . fb = facebook . GraphAPI ( token ) except : print ( "Couldn't connect to fb" ) return False self . connected_to_fb = True ...
def F_oneway ( * lists ) : """Performs a 1 - way ANOVA , returning an F - value and probability given any number of groups . From Heiman , pp . 394-7. Usage : F _ oneway ( * lists ) where * lists is any number of lists , one per treatment group Returns : F value , one - tailed p - value"""
a = len ( lists ) # ANOVA on ' a ' groups , each in it ' s own list means = [ 0 ] * a vars = [ 0 ] * a ns = [ 0 ] * a alldata = [ ] tmp = lists means = map ( mean , tmp ) vars = map ( var , tmp ) ns = map ( len , lists ) for i in range ( len ( lists ) ) : alldata = alldata + lists [ i ] bign = len ( alldata ) sstot...
def target_to_hostname ( target ) : """Attempt to return a single hostname list from a target string ."""
if len ( target ) == 0 or len ( target ) > 255 : return None if not re . match ( r'^[\w.-]+$' , target ) : return None return [ target ]
def parse_collection ( location : str , base_item_type : Type [ T ] , item_name_for_log : str = None , file_mapping_conf : FileMappingConfiguration = None , logger : Logger = default_logger , lazy_mfcollection_parsing : bool = False ) -> Dict [ str , T ] : """Utility method to create a RootParser ( ) with default c...
rp = _create_parser_from_default ( logger ) opts = create_parser_options ( lazy_mfcollection_parsing = lazy_mfcollection_parsing ) return rp . parse_collection ( location , base_item_type , item_name_for_log = item_name_for_log , file_mapping_conf = file_mapping_conf , options = opts )
def touch2screen ( w , h , o , x , y ) : '''convert touch position'''
if o == 0 : return x , y elif o == 1 : # landscape - right return y , w - x elif o == 2 : # upsidedown return w - x , h - y elif o == 3 : # landscape - left return h - y , x return x , y
def impulse_deltav_plummerstream ( v , y , b , w , GSigma , rs , tmin = None , tmax = None ) : """NAME : impulse _ deltav _ plummerstream PURPOSE : calculate the delta velocity to due an encounter with a Plummer - softened stream in the impulse approximation ; allows for arbitrary velocity vectors , but y is ...
if len ( v . shape ) == 1 : v = numpy . reshape ( v , ( 1 , 3 ) ) y = numpy . reshape ( y , ( 1 , 1 ) ) if tmax is None or tmax is None : raise ValueError ( "tmin= and tmax= need to be set" ) nv = v . shape [ 0 ] vmag = numpy . sqrt ( numpy . sum ( v ** 2. , axis = 1 ) ) # Build the rotation matrices and th...
def run_analysis ( self , argv ) : """Run this analysis"""
args = self . _parser . parse_args ( argv ) name_keys = dict ( target_type = args . ttype , target_name = args . target , sim_name = args . sim , fullpath = True ) orig_dir = NAME_FACTORY . targetdir ( ** name_keys ) dest_dir = NAME_FACTORY . sim_targetdir ( ** name_keys ) self . copy_target_dir ( orig_dir , dest_dir ,...
def delete ( gandi , resource ) : """Delete DNSSEC key ."""
result = gandi . dnssec . delete ( resource ) gandi . echo ( 'Delete successful.' ) return result
def fcoe_fcoe_fabric_map_fcoe_fabric_mode ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe = ET . SubElement ( config , "fcoe" , xmlns = "urn:brocade.com:mgmt:brocade-fcoe" ) fcoe_fabric_map = ET . SubElement ( fcoe , "fcoe-fabric-map" ) fcoe_fabric_map_name_key = ET . SubElement ( fcoe_fabric_map , "fcoe-fabric-map-name" ) fcoe_fabric_map_name_key . text = kwargs . po...
def _plunge ( tasks , pausing , finish ) : """( internal ) calls the next method of weaved tasks until they are finished or The ` ` Plumber ` ` instance is stopped see : ` ` Dagger . chinkup ` ` ."""
# If no result received either not started or start & stop # could have been called before the plunger thread while True : if pausing ( ) : tasks . stop ( ) try : tasks . next ( ) except StopIteration : finish ( pausing ( ) ) break
def PointCollection ( mode = "raw" , * args , ** kwargs ) : """mode : string - " raw " ( speed : fastest , size : small , output : ugly ) - " agg " ( speed : fast , size : small , output : beautiful )"""
if mode == "raw" : return RawPointCollection ( * args , ** kwargs ) return AggPointCollection ( * args , ** kwargs )
def set_flowcontrol_receive ( self , name , value = None , default = False , disable = False ) : """Configures the interface flowcontrol receive value Args : name ( string ) : The interface identifier . It must be a full interface name ( ie Ethernet , not Et ) value ( boolean ) : True if the interface shoul...
return self . set_flowcontrol ( name , 'receive' , value , default , disable )
def get_product_url ( self , force_http = False ) : """Creates base url of product location on AWS . : param force _ http : True if HTTP base URL should be used and False otherwise : type force _ http : str : return : url of product location : rtype : str"""
base_url = self . base_http_url if force_http else self . base_url return '{}products/{}/{}' . format ( base_url , self . date . replace ( '-' , '/' ) , self . product_id )
def update_session_variables ( self , variables_mapping ) : """update session with extracted variables mapping . these variables are valid in the whole running session ."""
variables_mapping = utils . ensure_mapping_format ( variables_mapping ) self . session_variables_mapping . update ( variables_mapping ) self . test_variables_mapping . update ( self . session_variables_mapping )
def create_rt_extended_community ( value , subtype = 2 ) : """Creates an instance of the BGP Route Target Community ( if " subtype = 2 " ) or Route Origin Community ( " subtype = 3 " ) . : param value : String of Route Target or Route Origin value . : param subtype : Subtype of Extended Community . : return...
global_admin , local_admin = value . split ( ':' ) local_admin = int ( local_admin ) if global_admin . isdigit ( ) and 0 <= int ( global_admin ) <= 0xffff : ext_com = BGPTwoOctetAsSpecificExtendedCommunity ( subtype = subtype , as_number = int ( global_admin ) , local_administrator = local_admin ) elif global_admin...
def spreadsheet2gradebook ( self , csv_file , email_field = None , approve_grades = False , use_max_points_column = False , max_points_column = None , normalize_column = None ) : """Upload grade spreadsheet to gradebook . Upload grades from CSV format spreadsheet file into the Learning Modules gradebook . The s...
non_assignment_fields = [ 'ID' , 'Username' , 'Full Name' , 'edX email' , 'External email' ] if max_points_column is not None : non_assignment_fields . append ( max_points_column ) if normalize_column is not None : non_assignment_fields . append ( normalize_column ) if email_field is not None : non_assignme...
def get_include ( ) : '''return a list of include directories .'''
dirname = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) ) ) # Header files may be stored in different relative locations # depending on installation mode ( e . g . , ` python setup . py install ` , # ` python setup . py develop ` . The first entry in each list is # where develop - mode heade...
def _get_blkid_type ( self ) : """Retrieves the FS type from the blkid command ."""
try : result = _util . check_output_ ( [ 'blkid' , '-p' , '-O' , str ( self . offset ) , self . get_raw_path ( ) ] ) if not result : return None # noinspection PyTypeChecker blkid_result = dict ( re . findall ( r'([A-Z]+)="(.+?)"' , result ) ) self . info [ 'blkid_data' ] = blkid_result ...
def logs ( awsclient , function_name , start_dt , end_dt = None , tail = False ) : """Send a ping request to a lambda function . : param awsclient : : param function _ name : : param start _ dt : : param end _ dt : : param tail : : return :"""
log . debug ( 'Getting cloudwatch logs for: %s' , function_name ) log_group_name = '/aws/lambda/%s' % function_name current_date = None start_ts = datetime_to_timestamp ( start_dt ) if end_dt : end_ts = datetime_to_timestamp ( end_dt ) else : end_ts = None # tail mode # we assume that logs can arrive late but n...
def waverange ( self ) : """Range of ` waveset ` ."""
if self . waveset is None : x = [ None , None ] else : x = u . Quantity ( [ self . waveset . min ( ) , self . waveset . max ( ) ] ) return x
def _iter ( root , term ) : '''Checks for python2.6 or python2.7'''
if sys . version_info < ( 2 , 7 ) : return root . getiterator ( term ) else : return root . iter ( term )
def namedb_is_name_zonefile_hash ( cur , name , zonefile_hash ) : """Determine if a zone file hash was sent by a name . Return True if so , false if not"""
select_query = 'SELECT COUNT(value_hash) FROM history WHERE history_id = ? AND value_hash = ?' select_args = ( name , zonefile_hash ) rows = namedb_query_execute ( cur , select_query , select_args ) count = None for r in rows : count = r [ 'COUNT(value_hash)' ] break return count > 0
def has_column ( self , table , column ) : """Determine if the given table has a given column . : param table : The table : type table : str : type column : str : rtype : bool"""
column = column . lower ( ) return column in list ( map ( lambda x : x . lower ( ) , self . get_column_listing ( table ) ) )
def fit_candidates ( AggOp , B , tol = 1e-10 ) : """Fit near - nullspace candidates to form the tentative prolongator . Parameters AggOp : csr _ matrix Describes the sparsity pattern of the tentative prolongator . Has dimension ( # blocks , # aggregates ) B : array The near - nullspace candidates stored...
if not isspmatrix_csr ( AggOp ) : raise TypeError ( 'expected csr_matrix for argument AggOp' ) B = np . asarray ( B ) if B . dtype not in [ 'float32' , 'float64' , 'complex64' , 'complex128' ] : B = np . asarray ( B , dtype = 'float64' ) if len ( B . shape ) != 2 : raise ValueError ( 'expected 2d array for ...
def potential ( __func__ = None , ** kwds ) : """Decorator function instantiating potentials . Usage : @ potential def B ( parent _ name = . , . . . ) return baz ( parent _ name , . . . ) where baz returns the deterministic B ' s value conditional on its parents . : SeeAlso : Deterministic , determini...
def instantiate_pot ( __func__ ) : junk , parents = _extract ( __func__ , kwds , keys , 'Potential' , probe = False ) return Potential ( parents = parents , ** kwds ) keys = [ 'logp' ] instantiate_pot . kwds = kwds if __func__ : return instantiate_pot ( __func__ ) return instantiate_pot
def outline_segments ( self , mask_background = False ) : """Outline the labeled segments . The " outlines " represent the pixels * just inside * the segments , leaving the background pixels unmodified . Parameters mask _ background : bool , optional Set to ` True ` to mask the background pixels ( labels ...
from scipy . ndimage import grey_erosion , grey_dilation # mode = ' constant ' ensures outline is included on the image borders selem = np . array ( [ [ 0 , 1 , 0 ] , [ 1 , 1 , 1 ] , [ 0 , 1 , 0 ] ] ) eroded = grey_erosion ( self . data , footprint = selem , mode = 'constant' , cval = 0. ) dilated = grey_dilation ( sel...
def convert ( model , input_features , output_features ) : """Convert a normalizer model to the protobuf spec . Parameters model : Normalizer A Normalizer . input _ features : str Name of the input column . output _ features : str Name of the output column . Returns model _ spec : An object of typ...
if not ( _HAS_SKLEARN ) : raise RuntimeError ( 'scikit-learn not found. scikit-learn conversion API is disabled.' ) # Test the scikit - learn model _sklearn_util . check_expected_type ( model , Normalizer ) _sklearn_util . check_fitted ( model , lambda m : hasattr ( m , 'norm' ) ) # Set the interface params . spec ...
def get_application ( * args ) : '''Returns a WSGI application function . If you supply the WSGI app and config it will use that , otherwise it will try to obtain them from a local Salt installation'''
opts_tuple = args def wsgi_app ( environ , start_response ) : root , _ , conf = opts_tuple or bootstrap_app ( ) cherrypy . config . update ( { 'environment' : 'embedded' } ) cherrypy . tree . mount ( root , '/' , conf ) return cherrypy . tree ( environ , start_response ) return wsgi_app
def run ( self ) : """Runs the scanner : return : self"""
# Normalize path self . path = os . path . expanduser ( self . path ) # Start scanning if os . path . isdir ( self . path ) : self . search_script_directory ( self . path ) return self else : raise ScannerException ( "Unknown directory: %s" % self . path )
def os_version ( self , value ) : """The os _ version property . Args : value ( string ) . the property value ."""
if value == self . _defaults [ 'ai.device.osVersion' ] and 'ai.device.osVersion' in self . _values : del self . _values [ 'ai.device.osVersion' ] else : self . _values [ 'ai.device.osVersion' ] = value
def webui_schematics_panels_panel_components_component_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) webui = ET . SubElement ( config , "webui" , xmlns = "http://tail-f.com/ns/webui" ) schematics = ET . SubElement ( webui , "schematics" ) panels = ET . SubElement ( schematics , "panels" ) panel = ET . SubElement ( panels , "panel" ) name_key = ET . SubElement ( panel , "name" ) name_...
def format_search_results ( self , search_results ) : """Format search results . Args : search _ results ( list of ` ResourceSearchResult ` ) : Search to format . Returns : List of 2 - tuple : Text and color to print in ."""
formatted_lines = [ ] for search_result in search_results : lines = self . _format_search_result ( search_result ) formatted_lines . extend ( lines ) return formatted_lines
def add_consumer ( self , consumer ) : """Add another consumer from a : class : ` Consumer ` instance ."""
consumer . backend = self . backend self . consumers . append ( consumer )
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'document_id' ) and self . document_id is not None : _dict [ 'document_id' ] = self . document_id if hasattr ( self , 'passage_score' ) and self . passage_score is not None : _dict [ 'passage_score' ] = self . passage_score if hasattr ( self , 'passage_text' ) and self . passage_...
def del_doc ( self , doc ) : """Delete a document"""
logger . info ( "Removing doc from the index: %s" % doc ) doc = doc . clone ( ) # make sure it can be serialized safely self . docsearch . index . del_doc ( doc )
def light_to_gl ( light , transform , lightN ) : """Convert trimesh . scene . lighting . Light objects into args for gl . glLightFv calls Parameters light : trimesh . scene . lighting . Light Light object to be converted to GL transform : ( 4 , 4 ) float Transformation matrix of light lightN : int R...
# convert color to opengl gl_color = vector_to_gl ( light . color . astype ( np . float64 ) / 255.0 ) assert len ( gl_color ) == 4 # cartesian translation from matrix gl_position = vector_to_gl ( transform [ : 3 , 3 ] ) # create the different position and color arguments args = [ ( lightN , gl . GL_POSITION , gl_positi...
def set ( self , x , y , value ) : """Set the data at ( x , y ) to value ."""
xBase = int ( x ) * self . xScale yBase = int ( y ) * self . yScale for xOffset in range ( self . xScale ) : for yOffset in range ( self . yScale ) : self . data [ yBase + yOffset , xBase + xOffset ] = value
def extra_hosts ( self , value ) : """: param value : : return None :"""
if value is None : self . _extra_hosts = value elif isinstance ( value , list ) : # TODO : better validation self . _extra_hosts = value elif isinstance ( value , dict ) : converted_extra_hosts = [ ] for k , v in sorted ( six . iteritems ( value ) ) : if not is_valid_hostname ( k ) : ...
def exit ( self , status = 0 , message = None ) : """Delegates to ` ArgumentParser . exit `"""
if status : self . logger . error ( message ) if self . __parser__ : # pylint : disable - msg = E1101 self . __parser__ . exit ( status , message ) # pylint : disable - msg = E1101 else : sys . exit ( status )
def get_attached_instruments ( self , expected : Dict [ Mount , str ] ) -> Dict [ Mount , Dict [ str , Optional [ str ] ] ] : """Find the instruments attached to our mounts . : param expected : A dict that may contain a mapping from mount to strings that should prefix instrument model names . When instruments...
to_return : Dict [ Mount , Dict [ str , Optional [ str ] ] ] = { } for mount in Mount : found_model = self . _smoothie_driver . read_pipette_model ( mount . name . lower ( ) ) found_id = self . _smoothie_driver . read_pipette_id ( mount . name . lower ( ) ) expected_instr = expected . get ( mount , None ) ...
def indent_files ( arguments ) : """indent _ files ( fname : str ) 1 . Creates a backup of the source file ( backup _ source _ file ( ) ) 2 . Reads the files contents ( read _ file ( ) ) 3 . Indents the code ( indent _ code ( ) ) 4 . Writes the file or print the indented code ( _ after _ indentation ( ) )""...
opts = parse_options ( arguments ) if not opts . files : # Indent from stdin code = sys . stdin . read ( ) indent_result = indent_code ( code , opts ) _after_indentation ( indent_result ) for fname in opts . files : code = read_file ( fname ) if not opts . dialect : # Guess dialect from the file ext...
def settlement_date ( self , value ) : """Force the settlement _ date to always be a date : param value : : return :"""
if value : self . _settlement_date = parse ( value ) . date ( ) if isinstance ( value , type_check ) else value
def _get_instance ( project_id , instance_zone , name , service ) : '''Get instance details'''
return service . instances ( ) . get ( project = project_id , zone = instance_zone , instance = name ) . execute ( )
def delete ( self ) : """Delete the cloud from the list of added clouds in mist . io service . : returns : A list of mist . clients ' updated clouds ."""
req = self . request ( self . mist_client . uri + '/clouds/' + self . id ) req . delete ( ) self . mist_client . update_clouds ( )
def covariance ( self , param_1 , param_2 ) : """Return the covariance between param _ 1 and param _ 2. : param param _ 1 : ` ` Parameter ` ` Instance . : param param _ 2 : ` ` Parameter ` ` Instance . : return : Covariance of the two params ."""
param_1_number = self . model . params . index ( param_1 ) param_2_number = self . model . params . index ( param_2 ) return self . covariance_matrix [ param_1_number , param_2_number ]
def rewriteFasta ( sequence , sequence_name , fasta_in , fasta_out ) : """Rewrites a specific sequence in a multifasta file while keeping the sequence header . : param sequence : a string with the sequence to be written : param sequence _ name : the name of the sequence to be retrieved eg . for ' > 2 dna : chro...
f = open ( fasta_in , 'r+' ) f2 = open ( fasta_out , 'w' ) lines = f . readlines ( ) i = 0 while i < len ( lines ) : line = lines [ i ] if line [ 0 ] == ">" : f2 . write ( line ) fChr = line . split ( " " ) [ 0 ] fChr = fChr [ 1 : ] if fChr == sequence_name : code = [...
def Logs ( loggername , echo = True , debug = False , chatty = False , loglevel = logging . INFO , logfile = None , logpath = None , fileHandler = None ) : """Initialize logging"""
log = logging . getLogger ( loggername ) if fileHandler is None : if logfile is None : logFilename = _ourName else : logFilename = logfile if '.log' not in logFilename : logFilename = '%s.log' % logFilename if logpath is not None : logFilename = os . path . join ( logpath...
def imbalance_metrics ( data ) : """Computes imbalance metric for a given dataset . Imbalance metric is equal to 0 when a dataset is perfectly balanced ( i . e . number of in each class is exact ) . : param data : pandas . DataFrame A dataset in a panda ' s data frame : returns int A value of imbalance me...
if not data : return 0 # imb - shows measure of inbalance within a dataset imb = 0 num_classes = float ( len ( Counter ( data ) ) ) for x in Counter ( data ) . values ( ) : p_x = float ( x ) / len ( data ) if p_x > 0 : imb += ( p_x - 1 / num_classes ) * ( p_x - 1 / num_classes ) # worst case scenari...
def base_list_parser ( ) : """Creates a parser with arguments specific to formatting lists of resources . Returns : { ArgumentParser } : Base parser with defaul list args"""
base_parser = ArgumentParser ( add_help = False ) base_parser . add_argument ( '-F' , '--format' , action = 'store' , default = 'default' , choices = [ 'csv' , 'json' , 'yaml' , 'default' ] , help = 'choose the output format' ) return base_parser
def iter_filth_clss ( ) : """Iterate over all of the filths that are included in this sub - package . This is a convenience method for capturing all new Filth that are added over time ."""
return iter_subclasses ( os . path . dirname ( os . path . abspath ( __file__ ) ) , Filth , _is_abstract_filth , )
def bootstrap_buttons ( parser , token ) : """Render buttons for form * * Tag name * * : : buttons * * Parameters * * : submit Text for a submit button reset Text for a reset button * * Usage * * : : { % buttons % } { % endbuttons % } * * Example * * : : { % buttons submit = ' OK ' reset = " C...
kwargs = parse_token_contents ( parser , token ) kwargs [ "nodelist" ] = parser . parse ( ( "endbuttons" , ) ) parser . delete_first_token ( ) return ButtonsNode ( ** kwargs )
def bulk_load ( self , ** kwargs ) : """Uploads data to the Blazegraph Triplestore that is stored in files that are in a local directory kwargs : file _ directory : a string path to the file directory file _ extensions : a list of file extensions to filter example [ ' xml ' , ' rdf ' ] . If none include a...
namespace = kwargs . get ( 'namespace' , self . namespace ) graph = kwargs . get ( 'graph' , self . graph ) if kwargs . get ( 'reset' ) == True : self . reset_namespace ( ) file_directory = kwargs . get ( 'file_directory' , self . local_directory ) file_extensions = kwargs . get ( 'file_extensions' , self . rdf_for...
def stats_send ( self , template , start_date , end_date , options = None ) : """Retrieve information about a particular transactional or aggregated information from transactionals from that template over a specified date range . http : / / docs . sailthru . com / api / stat"""
options = options or { } data = options . copy ( ) data = { 'template' : template , 'start_date' : start_date , 'end_date' : end_date } data [ 'stat' ] = 'send' return self . _stats ( data )
def link_connection_to_account ( app ) : """Link the connection to your Heroku user account . https : / / devcenter . heroku . com / articles / heroku - connect - api # step - 3 - link - the - connection - to - your - heroku - user - account"""
url = os . path . join ( settings . HEROKU_CONNECT_API_ENDPOINT , 'users' , 'me' , 'apps' , app , 'auth' ) response = requests . post ( url = url , headers = _get_authorization_headers ( ) ) response . raise_for_status ( )
def sum ( self ) : """Evaluate the integral over the given interval using Clenshaw - Curtis quadrature ."""
ak = self . coefficients ( ) ak2 = ak [ : : 2 ] n = len ( ak2 ) Tints = 2 / ( 1 - ( 2 * np . arange ( n ) ) ** 2 ) val = np . sum ( ( Tints * ak2 . T ) . T , axis = 0 ) a_ , b_ = self . domain ( ) return 0.5 * ( b_ - a_ ) * val
def chromaticity_to_XYZ ( white , red , green , blue ) : """From the " CalRGB Color Spaces " section of " PDF Reference " , 6th ed ."""
xW , yW = white xR , yR = red xG , yG = green xB , yB = blue R = G = B = 1.0 z = yW * ( ( xG - xB ) * yR - ( xR - xB ) * yG + ( xR - xG ) * yB ) YA = yR / R * ( ( xG - xB ) * yW - ( xW - xB ) * yG + ( xW - xG ) * yB ) / z XA = YA * xR / yR ZA = YA * ( ( 1 - xR ) / yR - 1 ) YB = - yG / G * ( ( xR - xB ) * yW - ( xW - xB...
def main ( argv ) : """Main ."""
del argv # Unused . if flags . FLAGS . version : print ( "GRR frontend {}" . format ( config_server . VERSION [ "packageversion" ] ) ) return config . CONFIG . AddContext ( "HTTPServer Context" ) server_startup . Init ( ) httpd = CreateServer ( ) server_startup . DropPrivileges ( ) try : httpd . serve_forev...
def add_perm ( self , subj_str , perm_str ) : """Add a permission for a subject . Args : subj _ str : str Subject for which to add permission ( s ) perm _ str : str Permission to add . Implicitly adds all lower permissions . E . g . , ` ` write ` ` will also add ` ` read ` ` ."""
self . _assert_valid_permission ( perm_str ) self . _perm_dict . setdefault ( perm_str , set ( ) ) . add ( subj_str )
def get_configs ( self ) : """: return : overall index , agent config , loadout config in that order"""
loadout_config = self . loadout_preset . config . copy ( ) config_path = None if self . agent_preset . config_path is not None : # Might be none if preset was never saved to disk . config_path = os . path . dirname ( self . agent_preset . config_path ) config = self . agent_preset . config . copy ( ) config . set_v...
def _validate_freq ( self ) : """Validate & return window frequency ."""
from pandas . tseries . frequencies import to_offset try : return to_offset ( self . window ) except ( TypeError , ValueError ) : raise ValueError ( "passed window {0} is not " "compatible with a datetimelike " "index" . format ( self . window ) )
def gopro_set_request_encode ( self , target_system , target_component , cmd_id , value ) : '''Request to set a GOPRO _ COMMAND with a desired target _ system : System ID ( uint8 _ t ) target _ component : Component ID ( uint8 _ t ) cmd _ id : Command ID ( uint8 _ t ) value : Value ( uint8 _ t )'''
return MAVLink_gopro_set_request_message ( target_system , target_component , cmd_id , value )
def remove_host ( self , host ) : """Called when the control connection observes that a node has left the ring . Intended for internal use only ."""
if host and self . metadata . remove_host ( host ) : log . info ( "Cassandra host %s removed" , host ) self . on_remove ( host )
def create ( self , file_or_path = None , data = None , obj_name = None , content_type = None , etag = None , content_encoding = None , content_length = None , ttl = None , chunked = False , metadata = None , chunk_size = None , headers = None , return_none = False ) : """Creates or replaces a storage object in thi...
return self . object_manager . create ( file_or_path = file_or_path , data = data , obj_name = obj_name , content_type = content_type , etag = etag , content_encoding = content_encoding , content_length = content_length , ttl = ttl , chunked = chunked , metadata = metadata , chunk_size = chunk_size , headers = headers ...
def configuration_callback ( cmd_name , option_name , config_file_name , saved_callback , provider , implicit , ctx , param , value ) : """Callback for reading the config file . Also takes care of calling user specified custom callback afterwards . cmd _ name : str The command name . This is used to determine...
ctx . default_map = ctx . default_map or { } cmd_name = cmd_name or ctx . info_name if implicit : default_value = os . path . join ( click . get_app_dir ( cmd_name ) , config_file_name ) param . default = default_value value = value or default_value if value : try : config = provider ( value , c...
def solve_potts_approx ( y , w , gamma = None , min_size = 1 , ** kw ) : """Fit penalized stepwise constant function ( Potts model ) to data approximatively , in linear time . Do this by running the exact solver using a small maximum interval size , and then combining consecutive intervals together if it de...
n = len ( y ) if n == 0 : return [ ] , [ ] , [ ] mu_dist = kw . get ( 'mu_dist' ) if mu_dist is None : mu_dist = get_mu_dist ( y , w ) kw [ 'mu_dist' ] = mu_dist if gamma is None : mu , dist = mu_dist . mu , mu_dist . dist gamma = 3 * dist ( 0 , n - 1 ) * math . log ( n ) / n if min_size < 10 : ...
def to_api_repr ( self ) : """Generate a resource for : meth : ` _ begin ` ."""
configuration = self . _configuration . to_api_repr ( ) resource = { "jobReference" : self . _properties [ "jobReference" ] , "configuration" : configuration , } configuration [ "query" ] [ "query" ] = self . query return resource
def _round_multiple ( x : int , mult : int = None ) -> int : "Calc ` x ` to nearest multiple of ` mult ` ."
return ( int ( x / mult + 0.5 ) * mult ) if mult is not None else x
def is_regex_type ( type_ ) : """Checks if the given type is a regex type . : param type _ : The type to check : return : True if the type is a regex type , otherwise False : rtype : bool"""
return ( callable ( type_ ) and getattr ( type_ , "__name__" , None ) == REGEX_TYPE_NAME and hasattr ( type_ , "__supertype__" ) and is_compiled_pattern ( type_ . __supertype__ ) )
def get_chat_member ( self , chat_id , user_id ) : """Use this method to get information about a member of a chat . Returns a ChatMember object on success . : param chat _ id : : param user _ id : : return :"""
result = apihelper . get_chat_member ( self . token , chat_id , user_id ) return types . ChatMember . de_json ( result )
def deploy_wsgi ( ) : """deploy python wsgi file ( s )"""
if 'libapache2-mod-wsgi' in get_packages ( ) : remote_dir = '/' . join ( [ deployment_root ( ) , 'env' , env . project_fullname , 'wsgi' ] ) wsgi = 'apache2' elif 'gunicorn' in get_packages ( ) : remote_dir = '/etc/init' wsgi = 'gunicorn' deployed = [ ] # ensure project apps path is also added to enviro...
def count ( self , * , page_size = DEFAULT_BATCH_SIZE , ** options ) : """Counts the number of entities that match this query . Note : Since Datastore doesn ' t provide a native way to count entities by query , this method paginates through all the entities ' keys and counts them . Parameters : \**optio...
entities = 0 options = QueryOptions ( self ) . replace ( keys_only = True ) for page in self . paginate ( page_size = page_size , ** options ) : entities += len ( list ( page ) ) return entities
def set_modifier_mapping ( self , keycodes ) : """Set the keycodes for the eight modifiers X . Shift , X . Lock , X . Control , X . Mod1 , X . Mod2 , X . Mod3 , X . Mod4 and X . Mod5 . keycodes should be a eight - element list where each entry is a list of the keycodes that should be bound to that modifier . ...
r = request . SetModifierMapping ( display = self . display , keycodes = keycodes ) return r . status
def prefetch_docker_image_on_private_agents ( image , timeout = timedelta ( minutes = 5 ) . total_seconds ( ) ) : """Given a docker image . An app with the image is scale across the private agents to ensure that the image is prefetched to all nodes . : param image : docker image name : type image : str : pa...
agents = len ( shakedown . get_private_agents ( ) ) app = { "id" : "/prefetch" , "instances" : agents , "container" : { "type" : "DOCKER" , "docker" : { "image" : image } } , "cpus" : 0.1 , "mem" : 128 } client = marathon . create_client ( ) client . add_app ( app ) shakedown . deployment_wait ( timeout ) shakedown . d...
def from_bytes ( cls , bitstream ) : '''Parse the given record and update properties accordingly'''
record = cls ( ) # Convert to ConstBitStream ( if not already provided ) if not isinstance ( bitstream , ConstBitStream ) : if isinstance ( bitstream , Bits ) : bitstream = ConstBitStream ( auto = bitstream ) else : bitstream = ConstBitStream ( bytes = bitstream ) # Read the priorities and weigh...
def duplicate_nodes ( self ) : """Return a sequence of node keys of identical meshes . Will combine meshes duplicated by copying in space with different keys in self . geometry , as well as meshes repeated by self . nodes . Returns duplicates : ( m ) sequence of keys to self . nodes that represent identic...
# if there is no geometry we can have no duplicate nodes if len ( self . geometry ) == 0 : return [ ] # geometry name : md5 of mesh mesh_hash = { k : int ( m . identifier_md5 , 16 ) for k , m in self . geometry . items ( ) } # the name of nodes in the scene graph with geometry node_names = np . array ( self . graph...
def _build_command ( self ) : """Command to start the QEMU process . ( to be passed to subprocess . Popen ( ) )"""
additional_options = self . _options . strip ( ) additional_options = additional_options . replace ( "%vm-name%" , '"' + self . _name . replace ( '"' , '\\"' ) + '"' ) additional_options = additional_options . replace ( "%vm-id%" , self . _id ) additional_options = additional_options . replace ( "%project-id%" , self ....
def source ( self , source ) : """When the source gets updated , update the select widget"""
if isinstance ( source , list ) : # if source is a list , get first item or None source = source [ 0 ] if len ( source ) > 0 else None self . _source = source
def get_unused_list_annotation_values ( graph ) -> Mapping [ str , Set [ str ] ] : """Get all of the unused values for list annotations . : param pybel . BELGraph graph : A BEL graph : return : A dictionary of { str annotation : set of str values that aren ' t used }"""
result = { } for annotation , values in graph . annotation_list . items ( ) : used_values = get_annotation_values ( graph , annotation ) if len ( used_values ) == len ( values ) : # all values have been used continue result [ annotation ] = set ( values ) - used_values return result