signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def to_pandas ( self ) : """Convert to pandas MultiIndex . Returns pandas . base . MultiIndex"""
if not all ( ind . is_raw ( ) for ind in self . values ) : raise ValueError ( 'Cannot convert to pandas MultiIndex if not evaluated.' ) from pandas import MultiIndex as PandasMultiIndex arrays = [ ind . values for ind in self . values ] return PandasMultiIndex . from_arrays ( arrays , names = self . names )
def mapToLineCol ( self , absPosition ) : """Convert absolute position to ` ` ( line , column ) ` `"""
block = self . document ( ) . findBlock ( absPosition ) if not block . isValid ( ) : raise IndexError ( "Invalid absolute position %d" % absPosition ) return ( block . blockNumber ( ) , absPosition - block . position ( ) )
def createRatModuleFromReadoutResolution ( inverseReadoutResolution , scale , enlargeModuleFactor = 1. , fixedScale = False , ** kwargs ) : """@ param inverseReadoutResolution ( int or float ) Equivalent to 1 / readoutResolution , but specified this way as a convenience ( because it ' s easier and less ambiguou...
params = computeRatModuleParametersFromReadoutResolution ( inverseReadoutResolution , enlargeModuleFactor ) params . update ( kwargs ) params [ "scale" ] = ( scale if fixedScale else scale * enlargeModuleFactor ) return ThresholdedGaussian2DLocationModule ( ** params )
def _make_key ( relation ) : """Make _ ReferenceKeys with lowercase values for the cache so we don ' t have to keep track of quoting"""
return _ReferenceKey ( _lower ( relation . database ) , _lower ( relation . schema ) , _lower ( relation . identifier ) )
def poll ( self ) : """Check if the operation has finished . : rtype : bool : returns : A boolean indicating if the current operation has completed . : raises ValueError : if the operation has already completed ."""
if self . complete : raise ValueError ( "The operation has completed." ) operation_pb = self . _get_operation ( ) self . _update_state ( operation_pb ) return self . complete
def create_tar_archive ( self ) : """Create a tar archive of the main simulation outputs ."""
# file filter EXCLUDE_FILES = glob . glob ( os . path . join ( self . savefolder , 'cells' ) ) EXCLUDE_FILES += glob . glob ( os . path . join ( self . savefolder , 'populations' , 'subsamples' ) ) EXCLUDE_FILES += glob . glob ( os . path . join ( self . savefolder , 'raw_nest_output' ) ) def filter_function ( tarinfo ...
def formatBodyNode ( root , path ) : '''Format the root node for use as the body node .'''
body = root body . name = "body" body . weight = calcFnWeight ( body ) body . path = path body . pclass = None return body
def add_route ( self , handle_cls , path , name , category , handle_params = { } , is_menu = False , order = time . time ( ) , is_open = True , oem = False , ** kwargs ) : """注册权限"""
if not path : return if path in self . routes : if self . routes [ path ] . get ( 'oem' ) : return self . routes [ path ] = dict ( path = path , # 权限url路径 name = name , # 权限名称 category = category , # 权限目录 is_menu = is_menu , # 是否在边栏显示为菜单 oprs = [ ] , # 关联的操作员 order = order , # 排序 is_open = is_open , # 是...
def keys ( self , key = None , reverse = False ) : """sort the keys before returning them"""
ks = sorted ( list ( dict . keys ( self ) ) , key = key , reverse = reverse ) return ks
def sort_list_by_index_list ( x : List [ Any ] , indexes : List [ int ] ) -> None : """Re - orders ` ` x ` ` by the list of ` ` indexes ` ` of ` ` x ` ` , in place . Example : . . code - block : : python from cardinal _ pythonlib . lists import sort _ list _ by _ index _ list z = [ " a " , " b " , " c " , "...
x [ : ] = [ x [ i ] for i in indexes ]
def pair ( address , key ) : '''Pair the bluetooth adapter with a device CLI Example : . . code - block : : bash salt ' * ' bluetooth . pair DE : AD : BE : EF : CA : FE 1234 Where DE : AD : BE : EF : CA : FE is the address of the device to pair with , and 1234 is the passphrase . TODO : This function is...
if not salt . utils . validate . net . mac ( address ) : raise CommandExecutionError ( 'Invalid BD address passed to bluetooth.pair' ) try : int ( key ) except Exception : raise CommandExecutionError ( 'bluetooth.pair requires a numerical key to be used' ) addy = address_ ( ) cmd = 'echo {0} | bluez-simple-...
def _calc_colour_hist ( img ) : """calculate colour histogram for each region the size of output histogram will be BINS * COLOUR _ CHANNELS ( 3) number of bins is 25 as same as [ uijlings _ ijcv2013 _ draft . pdf ] extract HSV"""
BINS = 25 hist = numpy . array ( [ ] ) for colour_channel in ( 0 , 1 , 2 ) : # extracting one colour channel c = img [ : , colour_channel ] # calculate histogram for each colour and join to the result hist = numpy . concatenate ( [ hist ] + [ numpy . histogram ( c , BINS , ( 0.0 , 255.0 ) ) [ 0 ] ] ) # L1 n...
def _Rzderiv ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ Rzderiv PURPOSE : evaluate the mixed R , z derivative for this potential INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : d2phi / dR / dz HISTORY : 2015-02-07 - Written - Bovy ( I...
return self . _mn3 [ 0 ] . Rzderiv ( R , z , phi = phi , t = t ) + self . _mn3 [ 1 ] . Rzderiv ( R , z , phi = phi , t = t ) + self . _mn3 [ 2 ] . Rzderiv ( R , z , phi = phi , t = t )
def iterrepos ( self ) : """A generator function that yields a ( repo , [ items ] ) tuple for each non - empty repo ."""
for repo , items in self . repo_items_hash . iteritems ( ) : if items : yield ( repo , items )
def update ( self ) : """Updates an instance within a project . For example : . . literalinclude : : snippets . py : start - after : [ START bigtable _ update _ instance ] : end - before : [ END bigtable _ update _ instance ] . . note : : Updates any or all of the following values : ` ` display _ name...
update_mask_pb = field_mask_pb2 . FieldMask ( ) if self . display_name is not None : update_mask_pb . paths . append ( "display_name" ) if self . type_ is not None : update_mask_pb . paths . append ( "type" ) if self . labels is not None : update_mask_pb . paths . append ( "labels" ) instance_pb = instance_...
def _get_obj_attr ( cls , obj , path , pos ) : """Resolve one kwargsql expression for a given object and returns its result . : param obj : the object to evaluate : param path : the list of all kwargsql expression , including those previously evaluated . : param int pos : provides index of the expression ...
field = path [ pos ] if isinstance ( obj , ( dict , Mapping ) ) : return obj [ field ] , pos elif isinstance ( obj , ( list , Sequence ) ) : join_operation = cls . SEQUENCE_OPERATIONS . get ( field ) if join_operation is not None : return ( AnySequenceResult ( cls . _sequence_map ( obj , path [ pos ...
def print_dedicated_access ( access ) : """Prints out the dedicated hosts a user can access"""
table = formatting . Table ( [ 'id' , 'Name' , 'Cpus' , 'Memory' , 'Disk' , 'Created' ] , 'Dedicated Access' ) for host in access : host_id = host . get ( 'id' ) host_fqdn = host . get ( 'name' ) host_cpu = host . get ( 'cpuCount' ) host_mem = host . get ( 'memoryCapacity' ) host_disk = host . get (...
def codes_get_string_array ( handle , key , size , length = None ) : # type : ( cffi . FFI . CData , bytes , int , int ) - > T . List [ bytes ] """Get string array values from a key . : param bytes key : the keyword whose value ( s ) are to be extracted : rtype : T . List [ bytes ]"""
if length is None : length = codes_get_string_length ( handle , key ) values_keepalive = [ ffi . new ( 'char[]' , length ) for _ in range ( size ) ] values = ffi . new ( 'char*[]' , values_keepalive ) size_p = ffi . new ( 'size_t *' , size ) _codes_get_string_array ( handle , key . encode ( ENC ) , values , size_p ...
def to_mongo ( qry ) : """Transform a simple query with one or more filter expressions into a MongoDB query expression . : param qry : Filter expression ( s ) , see function docstring for details . : type qry : str or list : return : MongoDB query : rtype : dict : raises : BadExpression , if one of the ...
rev = False # filters , not constraints # special case for empty string / list if qry == "" or qry == [ ] : return { } # break input into groups of filters unpar = lambda s : s . strip ( ) . strip ( '()' ) if isinstance ( qry , str ) : groups = [ ] if _TOK_OR in qry : groups = [ unpar ( g ) . split ...
def _get_resize_options ( self , dimensions ) : """: param dimensions : A tuple of ( width , height , force _ size ) . ' force _ size ' can be left off and will default to False ."""
if dimensions and isinstance ( dimensions , ( tuple , list ) ) : if len ( dimensions ) < 3 : dimensions = tuple ( dimensions ) + ( False , ) return dimensions
def undefinedImageType ( self ) : """Returns the name of undefined image type for the invalid image . . . versionadded : : 2.3.0"""
if self . _undefinedImageType is None : ctx = SparkContext . _active_spark_context self . _undefinedImageType = ctx . _jvm . org . apache . spark . ml . image . ImageSchema . undefinedImageType ( ) return self . _undefinedImageType
def uninstall_handle_input ( self ) : """Remove the hook ."""
if self . hooked is None : return ctypes . windll . user32 . UnhookWindowsHookEx ( self . hooked ) self . hooked = None
def tostype ( self , stype ) : """Return a copy of the array with chosen storage type . Returns NDArray or RowSparseNDArray A copy of the array with the chosen storage stype"""
# pylint : disable = no - member , protected - access if stype == 'csr' : raise ValueError ( "cast_storage from row_sparse to csr is not supported" ) return op . cast_storage ( self , stype = stype )
def calculate ( self , variable_name , period , ** parameters ) : """Calculate the variable ` ` variable _ name ` ` for the period ` ` period ` ` , using the variable formula if it exists . : returns : A numpy array containing the result of the calculation"""
population = self . get_variable_population ( variable_name ) holder = population . get_holder ( variable_name ) variable = self . tax_benefit_system . get_variable ( variable_name , check_existence = True ) if period is not None and not isinstance ( period , periods . Period ) : period = periods . period ( period ...
def gaussian_overlapping_coefficient ( means_0 , stds_0 , means_1 , stds_1 , lower = None , upper = None ) : """Compute the overlapping coefficient of two Gaussian continuous _ distributions . This computes the : math : ` \ int _ { - \ infty } ^ { \ infty } { \ min ( f ( x ) , g ( x ) ) \ partial x } ` where : ...
if lower is None : lower = - np . inf if upper is None : upper = np . inf def point_iterator ( ) : for ind in range ( means_0 . shape [ 0 ] ) : yield np . squeeze ( means_0 [ ind ] ) , np . squeeze ( stds_0 [ ind ] ) , np . squeeze ( means_1 [ ind ] ) , np . squeeze ( stds_1 [ ind ] ) return np . ar...
def _verify_create_args ( module_name , class_name , static ) : """Verifies a subset of the arguments to create ( )"""
# Verify module name is provided if module_name is None : raise InvalidServiceConfiguration ( 'Service configurations must define a module' ) # Non - static services must define a class if not static and class_name is None : tmpl0 = 'Non-static service configurations must define a class: ' tmpl1 = 'module i...
def event_list_tabs ( counts , current_kind , page_number = 1 ) : """Displays the tabs to different event _ list pages . ` counts ` is a dict of number of events for each kind , like : { ' all ' : 30 , ' gig ' : 12 , ' movie ' : 18 , } ` current _ kind ` is the event kind that ' s active , if any . e . g . ' ...
return { 'counts' : counts , 'current_kind' : current_kind , 'page_number' : page_number , # A list of all the kinds we might show tabs for , like # [ ' gig ' , ' movie ' , ' play ' , . . . ] 'event_kinds' : Event . get_kinds ( ) , # A dict of data about each kind , keyed by kind ( ' gig ' ) including # data about ' na...
def update ( self , filename = None , batch_id = None , prev_batch_id = None , producer = None , count = None , ) : """Creates an history model instance ."""
# TODO : refactor model enforce unique batch _ id # TODO : refactor model to not allow NULLs if not filename : raise BatchHistoryError ( "Invalid filename. Got None" ) if not batch_id : raise BatchHistoryError ( "Invalid batch_id. Got None" ) if not prev_batch_id : raise BatchHistoryError ( "Invalid prev_ba...
def locateChild ( self , ctx , segments ) : """Retrieve a L { SharingIndex } for a particular user , or rend . NotFound ."""
store = _storeFromUsername ( self . loginSystem . store , segments [ 0 ] . decode ( 'utf-8' ) ) if store is None : return rend . NotFound return ( SharingIndex ( store , self . webViewer ) , segments [ 1 : ] )
def block_events ( self ) : """Prevents the widget from sending signals ."""
self . _widget . blockSignals ( True ) self . _widget . setUpdatesEnabled ( False )
def register_domain ( self , domain = 0 , tokenizer = None , trie = None ) : """Register a domain with the intent engine . Args : tokenizer ( tokenizer ) : The tokenizer you wish to use . trie ( Trie ) : the Trie ( ) you wish to use . domain ( str ) : a string representing the domain you wish to add"""
self . domains [ domain ] = IntentDeterminationEngine ( tokenizer = tokenizer , trie = trie )
def find_element_by_id ( self , id_ , update = False ) -> Elements : '''Finds an element by id . Args : id _ : The id of the element to be found . update : If the interface has changed , this option should be True . Returns : The element if it was found . Raises : NoSuchElementException - If the eleme...
return self . find_element ( by = By . ID , value = id_ , update = update )
def dumps ( self , value ) : '''returns serialized ` value ` .'''
for serializer in self : value = serializer . dumps ( value ) return value
def _bind_target ( self , target , ctx = None ) : """Method to override in order to specialize binding of target . : param target : target to bind . : param ctx : target ctx . : return : bound target ."""
result = target try : # get annotations from target if exists . local_annotations = get_local_property ( target , Annotation . __ANNOTATIONS_KEY__ , [ ] , ctx = ctx ) except TypeError : raise TypeError ( 'target {0} must be hashable.' . format ( target ) ) # if local _ annotations do not exist , put them in tar...
def get_gallery_all ( self , username = '' , offset = 0 , limit = 10 ) : """Get all of a user ' s deviations : param username : The user to query , defaults to current user : param offset : the pagination offset : param limit : the pagination limit"""
if not username : raise DeviantartError ( 'No username defined.' ) response = self . _req ( '/gallery/all' , { 'username' : username , 'offset' : offset , 'limit' : limit } ) deviations = [ ] for item in response [ 'results' ] : d = Deviation ( ) d . from_dict ( item ) deviations . append ( d ) if "name...
def read_slice ( self , firstrow , lastrow , step = 1 , ** keys ) : """Read the specified row slice from a table . Read all rows between firstrow and lastrow ( non - inclusive , as per python slice notation ) . Note you must use slice notation for images , e . g . f [ ext ] [ 20:30 , 40:50] parameters fir...
if self . _info [ 'hdutype' ] == ASCII_TBL : rows = numpy . arange ( firstrow , lastrow , step , dtype = 'i8' ) keys [ 'rows' ] = rows return self . read_ascii ( ** keys ) step = keys . get ( 'step' , 1 ) if self . _info [ 'hdutype' ] == IMAGE_HDU : raise ValueError ( "slices currently only supported fo...
def merge_groups ( adata , key , map_groups , key_added = None , map_colors = None ) : """Parameters map _ colors : ` dict ` Dict with color specification for new groups that have no corresponding old group ."""
if key_added is None : key_added = key + '_merged' adata . obs [ key_added ] = adata . obs [ key ] . map ( map_groups ) . astype ( CategoricalDtype ( ) ) old_categories = adata . obs [ key ] . cat . categories new_categories = adata . obs [ key_added ] . cat . categories # map _ colors is passed if map_colors is no...
def get_filename ( self , instance ) : """Get the filename"""
filename = self . field . getFilename ( instance ) if filename : return filename fieldname = self . get_field_name ( ) content_type = self . get_content_type ( instance ) extension = mimetypes . guess_extension ( content_type ) return fieldname + extension
def _get_start_end ( parts , index = 7 ) : """Retrieve start and end for a VCF record , skips BNDs without END coords"""
start = parts [ 1 ] end = [ x . split ( "=" ) [ - 1 ] for x in parts [ index ] . split ( ";" ) if x . startswith ( "END=" ) ] if end : end = end [ 0 ] return start , end return None , None
def date_fromnow ( self , value ) : """Displays humanized date ( time since )"""
import humanize language = self . get_language ( ) if language != 'en' : humanize . i18n . activate ( language ) return Markup ( humanize . naturaltime ( value ) )
def forward ( inputs_i , Q , G , A , b , h , U_Q , U_S , R , verbose = False ) : """b = A z _ 0 h = G z _ 0 + s _ 0 U _ Q , U _ S , R = pre _ factor _ kkt ( Q , G , A , nineq , neq )"""
nineq , nz , neq , _ = get_sizes ( G , A ) # find initial values d = torch . ones ( nineq ) . type_as ( Q ) nb = - b if b is not None else None factor_kkt ( U_S , R , d ) x , s , z , y = solve_kkt ( U_Q , d , G , A , U_S , inputs_i , torch . zeros ( nineq ) . type_as ( Q ) , - h , nb ) # x1 , s1 , z1 , y1 = factor _ so...
def get_requirements ( opts ) : '''Get the proper requirements file based on the optional argument'''
if opts . dev : name = 'requirements_dev.txt' elif opts . doc : name = 'requirements_doc.txt' else : name = 'requirements.txt' requirements_file = os . path . join ( os . path . dirname ( __file__ ) , name ) install_requires = [ line . strip ( ) . replace ( '==' , '>=' ) for line in open ( requirements_file...
def delete_embedded ( self , rel = None , href = lambda _ : True ) : """Removes an embedded resource from this document . Calling code should use this method to remove embedded resources instead of modifying ` ` embedded ` ` directly . The optional arguments , ` ` rel ` ` and ` ` href ` ` are used to select t...
if EMBEDDED_KEY not in self . o : return if rel is None : for rel in list ( self . o [ EMBEDDED_KEY ] . keys ( ) ) : self . delete_embedded ( rel , href ) return if rel not in self . o [ EMBEDDED_KEY ] : return if callable ( href ) : url_filter = href else : url_filter = lambda x : x == ...
def detect ( self ) : """Detect IP and return it ."""
for theip in self . rips : LOG . debug ( "detected %s" , str ( theip ) ) self . set_current_value ( str ( theip ) ) return str ( theip )
def check_partial ( func , * args , ** kwargs ) : """Create a partial to be used by goodtables ."""
new_func = partial ( func , * args , ** kwargs ) new_func . check = func . check return new_func
def as_page ( self ) : """Wrap this Tag as a self - contained webpage . Create a page with the following structure : . . code - block : : html < ! DOCTYPE html > < html > < head > < meta http - equiv = " Content - type " content = " text / html " charset = " UTF - 8 " / > { self . resources } < ...
H = HTML ( ) utf8 = H . meta ( { 'http-equiv' : 'Content-type' } , content = "text/html" , charset = "UTF-8" ) return H . inline ( H . raw ( '<!DOCTYPE html>' ) , H . html ( H . head ( utf8 , * self . resources ) , H . body ( self ) ) )
def get_connectivity ( self , measure_name , plot = False ) : """Calculate spectral connectivity measure . Parameters measure _ name : str Name of the connectivity measure to calculate . See : class : ` Connectivity ` for supported measures . plot : { False , None , Figure object } , optional Whether and ...
if self . connectivity_ is None : raise RuntimeError ( "Connectivity requires a VAR model (run do_mvarica or fit_var first)" ) cm = getattr ( self . connectivity_ , measure_name ) ( ) cm = np . abs ( cm ) if np . any ( np . iscomplex ( cm ) ) else cm if plot is None or plot : fig = plot if self . plot_diago...
def enumerate_file_hash ( self , url , file_url , timeout = 15 , headers = { } ) : """Gets the MD5 of requests . get ( url + file _ url ) . @ param url : the installation ' s base URL . @ param file _ url : the url of the file to hash . @ param timeout : the number of seconds to wait prior to a timeout . @ ...
r = self . session . get ( url + file_url , timeout = timeout , headers = headers ) if r . status_code == 200 : hash = hashlib . md5 ( r . content ) . hexdigest ( ) return hash else : raise RuntimeError ( "File '%s' returned status code '%s'." % ( file_url , r . status_code ) )
def expiration_extractor ( widget , data ) : """Extract expiration information . - If active flag not set , Account is disabled ( value 0 ) . - If active flag set and value is UNSET , account never expires . - If active flag set and datetime choosen , account expires at given datetime . - Timestamp in sec...
active = int ( data . request . get ( '%s.active' % widget . name , '0' ) ) if not active : return 0 expires = data . extracted if expires : return time . mktime ( expires . utctimetuple ( ) ) return UNSET
def insertDataset ( self , blockcontent , otptIdList , migration = False ) : """This method insert a datsset from a block object into dbs ."""
dataset = blockcontent [ 'dataset' ] conn = self . dbi . connection ( ) # First , check and see if the dataset exists . try : datasetID = self . datasetid . execute ( conn , dataset [ 'dataset' ] ) dataset [ 'dataset_id' ] = datasetID except KeyError as ex : if conn : conn . close ( ) dbsExcepti...
def Clift ( Re ) : r'''Calculates drag coefficient of a smooth sphere using the method in [1 ] _ as described in [ 2 ] _ . . . math : : C _ D = \ left \ { \ begin { array } { ll } \ frac { 24 } { Re } + \ frac { 3 } { 16 } & \ mbox { if $ Re < 0.01 $ } \ \ \ frac { 24 } { Re } ( 1 + 0.1315Re ^ { 0.82 - 0....
if Re < 0.01 : Cd = 24. / Re + 3 / 16. elif Re < 20 : Cd = 24. / Re * ( 1 + 0.1315 * Re ** ( 0.82 - 0.05 * log10 ( Re ) ) ) elif Re < 260 : Cd = 24. / Re * ( 1 + 0.1935 * Re ** ( 0.6305 ) ) elif Re < 1500 : Cd = 10 ** ( 1.6435 - 1.1242 * log10 ( Re ) + 0.1558 * ( log10 ( Re ) ) ** 2 ) elif Re < 12000 : ...
def prune_empty_node ( node , seen ) : """Recursively remove empty branches and return whether this makes the node itself empty . The ` ` seen ` ` parameter is used to avoid infinite recursion due to cycles ( you never know ) ."""
if node . methods : return False if id ( node ) in seen : return True seen = seen | { id ( node ) } for branch in list ( node . branches ) : if prune_empty_node ( branch , seen ) : node . branches . remove ( branch ) else : return False return True
def trace ( ) : """trace finds the line , the filename and error message and returns it to the user"""
import traceback , inspect , sys tb = sys . exc_info ( ) [ 2 ] tbinfo = traceback . format_tb ( tb ) [ 0 ] filename = inspect . getfile ( inspect . currentframe ( ) ) # script name + line number line = tbinfo . split ( ", " ) [ 1 ] # Get Python syntax error synerror = traceback . format_exc ( ) . splitlines ( ) [ - 1 ]...
def set_helical_radius ( self , filename , bp , atomname = 'P' , full = False , bp_range = True ) : """To read and set local helical radius of both strand Parameters filename : str Input file , which is generated from do _ x3dna . e . g . HelixRad _ g . dat bp : 1D list or array base - pairs to analyze ...
if not ( isinstance ( bp , list ) or isinstance ( bp , np . ndarray ) ) : raise AssertionError ( "type %s is not list or np.ndarray" % type ( bp ) ) if not ( ( atomname == 'P' ) or ( atomname == 'O4*' ) or ( atomname == 'C1*' ) or ( atomname == 'O4\'' ) or ( atomname == 'C1\'' ) ) : print ( '\n This atomname {0...
def create ( self , recording_status_callback_event = values . unset , recording_status_callback = values . unset , recording_status_callback_method = values . unset , trim = values . unset , recording_channels = values . unset ) : """Create a new RecordingInstance : param unicode recording _ status _ callback _ ...
data = values . of ( { 'RecordingStatusCallbackEvent' : serialize . map ( recording_status_callback_event , lambda e : e ) , 'RecordingStatusCallback' : recording_status_callback , 'RecordingStatusCallbackMethod' : recording_status_callback_method , 'Trim' : trim , 'RecordingChannels' : recording_channels , } ) payload...
def columnclean ( column ) : """Modifies column header format to be importable into a database : param column : raw column header : return : cleanedcolumn : reformatted column header"""
cleanedcolumn = str ( column ) . replace ( '%' , 'percent' ) . replace ( '(' , '_' ) . replace ( ')' , '' ) . replace ( 'As' , 'Adenosines' ) . replace ( 'Cs' , 'Cytosines' ) . replace ( 'Gs' , 'Guanines' ) . replace ( 'Ts' , 'Thymines' ) . replace ( 'Ns' , 'Unknowns' ) . replace ( 'index' , 'adapterIndex' ) return cle...
def list_dvportgroups ( dvs = None , portgroup_names = None , service_instance = None ) : '''Returns a list of distributed virtual switch portgroups . The list can be filtered by the portgroup names or by the DVS . dvs Name of the DVS containing the portgroups . Default value is None . portgroup _ names ...
ret_dict = [ ] proxy_type = get_proxy_type ( ) if proxy_type == 'esxdatacenter' : datacenter = __salt__ [ 'esxdatacenter.get_details' ] ( ) [ 'datacenter' ] dc_ref = _get_proxy_target ( service_instance ) elif proxy_type == 'esxcluster' : datacenter = __salt__ [ 'esxcluster.get_details' ] ( ) [ 'datacenter'...
def get_linode ( kwargs = None , call = None ) : '''Returns data for a single named Linode . name The name of the Linode for which to get data . Can be used instead ` ` linode _ id ` ` . Note this will induce an additional API call compared to using ` ` linode _ id ` ` . linode _ id The ID of the Linode...
if call == 'action' : raise SaltCloudSystemExit ( 'The get_linode function must be called with -f or --function.' ) if kwargs is None : kwargs = { } name = kwargs . get ( 'name' , None ) linode_id = kwargs . get ( 'linode_id' , None ) if name is None and linode_id is None : raise SaltCloudSystemExit ( 'The ...
def get ( self ) : """Parse a response into string format and clear out its temporary containers : return : The parsed response message : rtype : str"""
self . _log . debug ( 'Converting Response object to string format' ) response = '' . join ( map ( str , self . _response ) ) . strip ( ) self . _log . debug ( 'Resetting parent Trigger temporary containers' ) self . stars = { 'normalized' : ( ) , 'case_preserved' : ( ) , 'raw' : ( ) } user = self . trigger . user self...
def parse_xml_boundary ( xml_region ) : """Get the geographic bounds from an XML element Args : xml _ region ( Element ) : The < region > tag as XML Element Returns : GeographicBB :"""
try : bounds = { } for boundary in xml_region . getchildren ( ) : bounds [ boundary . tag ] = float ( boundary . text ) bbox = GeographicBB ( min_lon = bounds [ "west" ] , max_lon = bounds [ "east" ] , min_lat = bounds [ "south" ] , max_lat = bounds [ "north" ] ) return bbox except ( KeyError , ...
def from_string ( cls , constraint ) : """: param str constraint : The string representation of a constraint : rtype : : class : ` MarathonConstraint `"""
obj = constraint . split ( ':' ) marathon_constraint = cls . from_json ( obj ) if marathon_constraint : return marathon_constraint raise ValueError ( "Invalid string format. " "Expected `field:operator:value`" )
def iter_column ( self , query = None , field = "_id" , ** kwargs ) : """Return one field as an iterator . Beware that if your query returns records where the field is not set , it will raise a KeyError ."""
find_kwargs = { "projection" : { "_id" : False } } find_kwargs [ "projection" ] [ field ] = True cursor = self . _collection_with_options ( kwargs ) . find ( query , ** find_kwargs ) # We only want 1 field : bypass the ORM patch_cursor ( cursor , ** kwargs ) return ( dotdict ( x ) [ field ] for x in cursor )
def _read_bits ( cls , raw_value ) : """Generator that takes a memory view and provides bitfields from it . After creating the generator , call ` send ( None ) ` to initialise it , and thereafter call ` send ( need _ bits ) ` to obtain that many bits ."""
have_bits = 0 bits = 0 byte_source = iter ( raw_value ) result = 0 while True : need_bits = yield result while have_bits < need_bits : try : bits = ( bits << 8 ) | int ( next ( byte_source ) ) have_bits += 8 except StopIteration : return result = int ( bit...
def echo ( message = None , file = None , nl = True , err = False , color = None , carriage_return = False ) : """Patched click echo function ."""
message = message or "" if carriage_return and nl : click_echo ( message + "\r\n" , file , False , err , color ) elif carriage_return and not nl : click_echo ( message + "\r" , file , False , err , color ) else : click_echo ( message , file , nl , err , color )
def pow2 ( x : int , p : int ) -> int : """= = pow ( x , 2 * * p , q )"""
while p > 0 : x = x * x % q p -= 1 return x
def extra_downloader_converter ( value ) : """Parses extra _ { downloader , converter } arguments . Parameters value : iterable or str If the value is a string , it is split into a list using spaces as delimiters . Otherwise , it is returned as is ."""
if isinstance ( value , six . string_types ) : value = value . split ( " " ) return value
def pckcov ( pck , idcode , cover ) : """Find the coverage window for a specified reference frame in a specified binary PCK file . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / pckcov _ c . html : param pck : Name of PCK file . : type pck : str : param idcode : Class ID c...
pck = stypes . stringToCharP ( pck ) idcode = ctypes . c_int ( idcode ) assert isinstance ( cover , stypes . SpiceCell ) assert cover . dtype == 1 libspice . pckcov_c ( pck , idcode , ctypes . byref ( cover ) )
async def start ( self ) : """Start api initialization ."""
_LOGGER . debug ( 'Initializing pyEight Version: %s' , __version__ ) await self . fetch_token ( ) if self . _token is not None : await self . fetch_device_list ( ) await self . assign_users ( ) return True else : # We couldn ' t authenticate return False
def dot_v2 ( vec1 , vec2 ) : """Return the dot product of two vectors"""
return vec1 . x * vec2 . x + vec1 . y * vec2 . y
def and_next ( e ) : """Create a PEG function for positive lookahead ."""
def match_and_next ( s , grm = None , pos = 0 ) : try : e ( s , grm , pos ) except PegreError as ex : raise PegreError ( 'Positive lookahead failed' , pos ) else : return PegreResult ( s , Ignore , ( pos , pos ) ) return match_and_next
def app_start ( name , profile , ** kwargs ) : """Start an application with specified profile . Does nothing if application is already running ."""
ctx = Context ( ** kwargs ) ctx . execute_action ( 'app:start' , ** { 'node' : ctx . repo . create_secure_service ( 'node' ) , 'name' : name , 'profile' : profile } )
def get_access_token ( self , method = 'POST' , decoder = parse_utf8_qsl , key = 'access_token' , ** kwargs ) : '''Returns an access token . : param method : A string representation of the HTTP method to be used , defaults to ` POST ` . : type method : str : param decoder : A function used to parse the Resp...
r = self . get_raw_access_token ( method , ** kwargs ) access_token , = process_token_request ( r , decoder , key ) return access_token
def serialisasi ( self ) : """Mengembalikan hasil serialisasi objek Entri ini . : returns : Dictionary hasil serialisasi : rtype : dict"""
return { "nama" : self . nama , "nomor" : self . nomor , "kata_dasar" : self . kata_dasar , "pelafalan" : self . pelafalan , "bentuk_tidak_baku" : self . bentuk_tidak_baku , "varian" : self . varian , "makna" : [ makna . serialisasi ( ) for makna in self . makna ] }
def _set_slave_enabled ( self , dpid , port , enabled ) : """set whether a slave i / f at some port of some datapath is enable or not ."""
slave = self . _get_slave ( dpid , port ) if slave : slave [ 'enabled' ] = enabled
def _excel2num ( x ) : """Convert Excel column name like ' AB ' to 0 - based column index . Parameters x : str The Excel column name to convert to a 0 - based column index . Returns num : int The column index corresponding to the name . Raises ValueError Part of the Excel column name was invalid ....
index = 0 for c in x . upper ( ) . strip ( ) : cp = ord ( c ) if cp < ord ( "A" ) or cp > ord ( "Z" ) : raise ValueError ( "Invalid column name: {x}" . format ( x = x ) ) index = index * 26 + cp - ord ( "A" ) + 1 return index - 1
def _contribute_to_class ( self , mcs_args : McsArgs ) : """Where the magic happens . Takes one parameter , the : class : ` McsArgs ` of the class - under - construction , and processes the declared ` ` class Meta ` ` from it ( if any ) . We fill ourself with the declared meta options ' name / value pairs , g...
self . _mcs_args = mcs_args Meta = mcs_args . clsdict . pop ( 'Meta' , None ) # type : Type [ object ] base_classes_meta = mcs_args . getattr ( 'Meta' , None ) # type : MetaOptionsFactory mcs_args . clsdict [ 'Meta' ] = self # must come before _ fill _ from _ meta , because # some meta options may depend upon having # ...
def url_encode ( obj , charset = 'utf-8' , encode_keys = False , sort = False , key = None , separator = '&' ) : """URL encode a dict / ` MultiDict ` . If a value is ` None ` it will not appear in the result string . Per default only values are encoded into the target charset strings . If ` encode _ keys ` is s...
return separator . join ( _url_encode_impl ( obj , charset , encode_keys , sort , key ) )
def jacobian_from_model ( model , as_functions = False ) : """Build a : class : ` ~ symfit . core . fit . CallableModel ` representing the Jacobian of ` ` model ` ` . This function make sure the chain rule is correctly applied for interdependent variables . : param model : Any symbolical model - type . : ...
# Inverse dict so we can turn functions back into vars in the end functions_as_vars = dict ( ( v , k ) for k , v in model . vars_as_functions . items ( ) ) # Create the jacobian components . The ` vars ` here in the model _ dict are # always of the type D ( y , a ) , but the righthand - side might still contain # funct...
def start_batch ( job , input_args ) : """This function will administer 5 jobs at a time then recursively call itself until subset is empty"""
samples = parse_sra ( input_args [ 'sra' ] ) # for analysis _ id in samples : job . addChildJobFn ( download_and_transfer_sample , input_args , samples , cores = 1 , disk = '30' )
def _callback ( self ) : """The actual callback ."""
if self . debug : # Show the number of open file descriptors print ( ">>>>> _callback: Number of open file descriptors: %s" % get_open_fds ( ) ) self . _runem_all ( ) # Mission accomplished . Shutdown the scheduler . all_ok = self . flow . all_ok if all_ok : return self . shutdown ( msg = "All tasks have reache...
def execute ( self , input_data ) : '''Execute the ViewMemoryDeep worker'''
# Aggregate the output from all the memory workers , clearly this could be kewler output = input_data [ 'view_memory' ] output [ 'tables' ] = { } for data in [ input_data [ key ] for key in ViewMemoryDeep . dependencies ] : for name , table in data [ 'tables' ] . iteritems ( ) : output [ 'tables' ] . update...
def _add_access_token_to_response ( self , response , access_token ) : # type : ( oic . message . AccessTokenResponse , se _ leg _ op . access _ token . AccessToken ) - > None """Adds the Access Token and the associated parameters to the Token Response ."""
response [ 'access_token' ] = access_token . value response [ 'token_type' ] = access_token . type response [ 'expires_in' ] = access_token . expires_in
def synchronized ( lock ) : """Synchronization decorator ; provide thread - safe locking on a function http : / / code . activestate . com / recipes / 465057/"""
def wrap ( f ) : def synchronize ( * args , ** kw ) : lock . acquire ( ) try : return f ( * args , ** kw ) finally : lock . release ( ) return synchronize return wrap
def name ( self ) : """User name ( the same name as on the users community profile page ) . : rtype : str"""
uid = self . user_id if self . _iface_user . get_id ( ) == uid : return self . _iface . get_my_name ( ) return self . _iface . get_name ( uid )
def print_help ( self , * args , ** kwargs ) : """Add pager support to help output ."""
if self . _command is not None and self . _command . session . allow_pager : desc = 'Help\: %s' % '-' . join ( self . prog . split ( ) ) pager_kwargs = self . _command . get_pager_spec ( ) with paging . pager_redirect ( desc , ** pager_kwargs ) : return super ( ) . print_help ( * args , ** kwargs ) ...
def get_language ( language_name ) : """Returns a callable that instantiates meta - model for the given language ."""
langs = list ( pkg_resources . iter_entry_points ( group = LANG_EP , name = language_name ) ) if not langs : raise TextXError ( 'Language "{}" is not registered.' . format ( language_name ) ) if len ( langs ) > 1 : # Multiple languages defined with the same name raise TextXError ( 'Language "{}" registered mult...
def calculate_tensor_to_probability_map_output_shapes ( operator ) : '''Allowed input / output patterns are ONNX < 1.2 1 . [ 1 , C ] - - - > - - - > A map 2 . [ 1 , C _ 1 , . . . , C _ n ] - - - > A map ONNX > = 1.2 1 . [ N , C ] - - - > - - - > A sequence of maps 2 . [ N , C _ 1 , . . . , C _ n ] - - -...
check_input_and_output_numbers ( operator , input_count_range = 1 , output_count_range = 1 ) check_input_and_output_types ( operator , good_input_types = [ FloatTensorType ] ) model_type = operator . raw_operator . WhichOneof ( 'Type' ) if model_type == 'neuralNetworkClassifier' : class_label_type = operator . raw_...
def populate ( self , source = DEFAULT_SEGMENT_SERVER , segments = None , pad = True , ** kwargs ) : """Query the segment database for this flag ' s active segments . This method assumes all of the metadata for each flag have been filled . Minimally , the following attributes must be filled . . autosummary : ...
tmp = DataQualityDict ( ) tmp [ self . name ] = self tmp . populate ( source = source , segments = segments , pad = pad , ** kwargs ) return tmp [ self . name ]
def file_put_contents ( self , path , data ) : """Put passed contents into file located at ' path '"""
path = self . get_full_file_path ( path ) # if file exists , create a temp copy to allow rollback if os . path . isfile ( path ) : tmp_path = self . new_tmp ( ) self . do_action ( { 'do' : [ 'copy' , path , tmp_path ] , 'undo' : [ 'move' , tmp_path , path ] } ) self . do_action ( { 'do' : [ 'write' , path , dat...
def batch_remove_retrain ( nmask_train , nmask_test , X_train , y_train , X_test , y_test , attr_train , attr_test , model_generator , metric ) : """An approximation of holdout that only retraines the model once . This is alse called ROAR ( RemOve And Retrain ) in work by Google . It is much more computationally ...
warnings . warn ( "The retrain based measures can incorrectly evaluate models in some cases!" ) X_train , X_test = to_array ( X_train , X_test ) # how many features to mask assert X_train . shape [ 1 ] == X_test . shape [ 1 ] # mask nmask top features for each explanation X_train_tmp = X_train . copy ( ) X_train_mean =...
def encode ( precision , with_z ) : """Given GeoJSON on stdin , writes a geobuf file to stdout ."""
logger = logging . getLogger ( 'geobuf' ) stdin = click . get_text_stream ( 'stdin' ) sink = click . get_binary_stream ( 'stdout' ) try : data = json . load ( stdin ) pbf = geobuf . encode ( data , precision if precision >= 0 else 6 , 3 if with_z else 2 ) sink . write ( pbf ) sys . exit ( 0 ) except Exc...
def count_star ( self ) -> int : """Implements the ` ` COUNT ( * ) ` ` specialization ."""
count_query = ( self . statement . with_only_columns ( [ func . count ( ) ] ) . order_by ( None ) ) return self . session . execute ( count_query ) . scalar ( )
def connectTo ( self , node , cls = None ) : """Creates a connection between this node and the inputed node . : param node | < XNode > cls | < subclass of XNodeConnection > | | None : return < XNodeConnection >"""
if ( not node ) : return con = self . scene ( ) . addConnection ( cls ) con . setOutputNode ( self ) con . setInputNode ( node ) return con
def sum ( data , start = 0 ) : """sum ( data [ , start ] ) - > value Return a high - precision sum of the given numeric data . If optional argument ` ` start ` ` is given , it is added to the total . If ` ` data ` ` is empty , ` ` start ` ` ( defaulting to 0 ) is returned ."""
n , d = exact_ratio ( start ) T = type ( start ) partials = { d : n } # map { denominator : sum of numerators } # Micro - optimizations . coerce_types_ = coerce_types exact_ratio_ = exact_ratio partials_get = partials . get # Add numerators for each denominator , and track the " current " type . for x in data : T =...
def push_to_topic ( dst , dat , qos = 0 , retain = False , cfgs = None ) : """- 发送数据 dat 到目的地 dst : param cfgs : : type cfgs : : param dst : : type dst : : param dat : : type dat : : param qos : : type qos : : param retain : : type retain :"""
cfg_amqt = { 'hostname' : cfgs [ 'hostname' ] , 'port' : cfgs [ 'port' ] , 'username' : cfgs [ 'username' ] , 'password' : cfgs [ 'password' ] , } msg = { 'topic' : dst , 'payload' : dat , 'qos' : qos , 'retain' : retain , } try : Publisher ( cfg_amqt ) . run ( msg ) return True except Exception as err : lo...
def reorderbydf ( df2 , df1 ) : """Reorder rows of a dataframe by other dataframe : param df2 : input dataframe : param df1 : template dataframe"""
df3 = pd . DataFrame ( ) for idx , row in df1 . iterrows ( ) : df3 = df3 . append ( df2 . loc [ idx , : ] ) return df3
def _find_home_or_away ( self , row ) : """Determine whether the player is on the home or away team . Next to every player is their school ' s name . This name can be matched with the previously parsed home team ' s name to determine if the player is a member of the home or away team . Parameters row : Py...
name = row ( 'td[data-stat="team"]' ) . text ( ) . upper ( ) if name == self . home_abbreviation . upper ( ) : return HOME else : return AWAY
def generate_harvestable_catalogs ( self , catalogs , harvest = 'all' , report = None , export_path = None ) : """Filtra los catálogos provistos según el criterio determinado en ` harvest ` . Args : catalogs ( str , dict o list ) : Uno ( str o dict ) o varios ( list de strs y / o dicts ) catálogos . ha...
assert isinstance ( catalogs , string_types + ( dict , list ) ) # Si se pasa un único catálogo , genero una lista que lo contenga if isinstance ( catalogs , string_types + ( dict , ) ) : catalogs = [ catalogs ] harvestable_catalogs = [ readers . read_catalog ( c ) for c in catalogs ] catalogs_urls = [ catalog if ...
def uuid ( uuid_value = None ) : """Returns a uuid value that is valid to use for id and identity fields . : return : unicode uuid object if using UUIDFields , uuid unicode string otherwise ."""
if uuid_value : if not validate_uuid ( uuid_value ) : raise ValueError ( "uuid_value must be a valid UUID version 4 object" ) else : uuid_value = uuid . uuid4 ( ) if versions_settings . VERSIONS_USE_UUIDFIELD : return uuid_value else : return six . u ( str ( uuid_value ) )
def _federation_indicators ( catalog , central_catalog , identifier_search = False ) : """Cuenta la cantidad de datasets incluídos tanto en la lista ' catalogs ' como en el catálogo central , y genera indicadores a partir de esa información . Args : catalog ( dict ) : catálogo ya parseado central _ ca...
result = { 'datasets_federados_cant' : None , 'datasets_federados_pct' : None , 'datasets_no_federados_cant' : None , 'datasets_federados_eliminados_cant' : None , 'distribuciones_federadas_cant' : None , 'datasets_federados_eliminados' : [ ] , 'datasets_no_federados' : [ ] , 'datasets_federados' : [ ] , } try : ce...