signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_composition_search_session ( self , proxy ) : """Gets a composition search session . arg proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . repository . CompositionSearchSession ) - a CompositionSearchSession raise : OperationFailed - unable to complete request raise : Unimplemented - supp...
if not self . supports_composition_search ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise # OperationFailed ( ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . CompositionSearchSession ( proxy , runtime = self . _runtime ) except AttributeErro...
def _process_status ( self , status ) : """Process latest status update ."""
self . _screen_id = status . get ( ATTR_SCREEN_ID ) self . status_update_event . set ( )
def pick ( self , connections ) : """Picks a connection with the earliest backoff time . As a result , the first connection is picked for as long as it has no backoff time . Otherwise , the connections are tried in a round robin fashion . Args : connections ( : obj : list ) : List of : class : ` ~ bigch...
if len ( connections ) == 1 : return connections [ 0 ] def key ( conn ) : return ( datetime . min if conn . backoff_time is None else conn . backoff_time ) return min ( * connections , key = key )
def _inherit_parent_kwargs ( self , kwargs ) : """Extract any necessary attributes from parent serializer to propagate down to child serializer ."""
if not self . parent or not self . _is_dynamic : return kwargs if 'request_fields' not in kwargs : # If ' request _ fields ' isn ' t explicitly set , pull it from the # parent serializer . request_fields = self . _get_request_fields_from_parent ( ) if request_fields is None : # Default to ' id _ only ' for ...
def version ( i ) : """Input : { } Output : { output from function ' get _ version '"""
o = i . get ( 'out' , '' ) r = get_version ( { } ) if r [ 'return' ] > 0 : return r version_str = r [ 'version_str' ] if o == 'con' : out ( 'V' + version_str ) return r
def decode_str ( s , free = False ) : """Decodes a SymbolicStr"""
try : if s . len == 0 : return u"" return ffi . unpack ( s . data , s . len ) . decode ( "utf-8" , "replace" ) finally : if free : lib . semaphore_str_free ( ffi . addressof ( s ) )
def get_readable ( self ) : '''Gets human - readable representation of the url ( as unicode string , IRI according RFC3987)'''
query = ( u'?' + u'&' . join ( u'{}={}' . format ( urlquote ( k ) , urlquote ( v ) ) for k , v in six . iteritems ( self . query ) ) if self . query else '' ) hash_part = ( u'#' + self . fragment ) if self . fragment is not None else u'' path , query , hash_part = uri_to_iri_parts ( self . path , query , hash_part ) if...
def filter_matrix_columns ( A , theta ) : """Filter each column of A with tol . i . e . , drop all entries in column k where abs ( A [ i , k ] ) < tol max ( abs ( A [ : , k ] ) ) Parameters A : sparse _ matrix theta : float In range [ 0,1 ) and defines drop - tolerance used to filter the columns of A ...
if not isspmatrix ( A ) : raise ValueError ( "Sparse matrix input needed" ) if isspmatrix_bsr ( A ) : blocksize = A . blocksize Aformat = A . format if ( theta < 0 ) or ( theta >= 1.0 ) : raise ValueError ( "theta must be in [0,1)" ) # Apply drop - tolerance to each column of A , which is most easily # acce...
def add_version_info ( matrix , version ) : """Adds the version information to the matrix , for versions < 7 this is a no - op . ISO / IEC 18004:2015 ( E ) - - 7.10 Version information ( page 58)"""
# module 0 = least significant bit # module 17 = most significant bit # Figure 27 — Version information positioning ( page 58) # Lower left Upper right # 0 3 6 9 12 15 0 1 2 # 1 4 7 10 13 16 3 4 5 # 2 5 8 11 14 17 6 7 8 # 9 10 11 # 12 13 14 # 15 16 17 if version < 7 : return version_info = consts . VERSION_INFO [ v...
def uninitialize_ui ( self ) : """Uninitializes the Component ui ."""
raise foundations . exceptions . ProgrammingError ( "{0} | '{1}' Component ui cannot be uninitialized!" . format ( self . __class__ . __name__ , self . name ) )
def rmse ( params1 , params2 ) : r"""Compute the root - mean - squared error between two models . Parameters params1 : array _ like Parameters of the first model . params2 : array _ like Parameters of the second model . Returns error : float Root - mean - squared error ."""
assert len ( params1 ) == len ( params2 ) params1 = np . asarray ( params1 ) - np . mean ( params1 ) params2 = np . asarray ( params2 ) - np . mean ( params2 ) sqrt_n = math . sqrt ( len ( params1 ) ) return np . linalg . norm ( params1 - params2 , ord = 2 ) / sqrt_n
def derivatives ( self , x , y , sigma0 , Rs , e1 , e2 , center_x = 0 , center_y = 0 ) : """returns df / dx and df / dy of the function ( integral of NFW )"""
phi_G , q = param_util . ellipticity2phi_q ( e1 , e2 ) x_shift = x - center_x y_shift = y - center_y cos_phi = np . cos ( phi_G ) sin_phi = np . sin ( phi_G ) e = abs ( 1 - q ) x_ = ( cos_phi * x_shift + sin_phi * y_shift ) * np . sqrt ( 1 - e ) y_ = ( - sin_phi * x_shift + cos_phi * y_shift ) * np . sqrt ( 1 + e ) f_x...
def parity_discover_next_available_nonce ( web3 : Web3 , address : AddressHex , ) -> Nonce : """Returns the next available nonce for ` address ` ."""
next_nonce_encoded = web3 . manager . request_blocking ( 'parity_nextNonce' , [ address ] ) return Nonce ( int ( next_nonce_encoded , 16 ) )
def main ( ) : """NAME dayplot _ magic . py DESCRIPTION makes ' day plots ' ( Day et al . 1977 ) and squareness / coercivity , plots ' linear mixing ' curve from Dunlop and Carter - Stiglitz ( 2006 ) . squareness coercivity of remanence ( Neel , 1955 ) plots after Tauxe et al . ( 2002) SYNTAX dayplo...
args = sys . argv if "-h" in args : print ( main . __doc__ ) sys . exit ( ) dir_path = pmag . get_named_arg ( '-WD' , '.' ) fmt = pmag . get_named_arg ( '-fmt' , 'svg' ) save_plots = False interactive = True if '-sav' in sys . argv : save_plots = True interactive = False infile = pmag . get_named_arg ( ...
def _process_converter ( self , f , filt = None ) : """Take a conversion function and possibly recreate the frame ."""
if filt is None : filt = lambda col , c : True needs_new_obj = False new_obj = dict ( ) for i , ( col , c ) in enumerate ( self . obj . iteritems ( ) ) : if filt ( col , c ) : new_data , result = f ( col , c ) if result : c = new_data needs_new_obj = True new_obj [ i ...
def sanitize_words ( self , words ) : """Guarantees that all textual symbols are unicode . Note : We do not convert numbers , only strings to unicode . We assume that the strings are encoded in utf - 8."""
_words = [ ] for w in words : if isinstance ( w , string_types ) and not isinstance ( w , unicode ) : _words . append ( unicode ( w , encoding = "utf-8" ) ) else : _words . append ( w ) return _words
def canonical_request ( self ) : """The AWS SigV4 canonical request given parameters from an HTTP request . This process is outlined here : http : / / docs . aws . amazon . com / general / latest / gr / sigv4 - create - canonical - request . html The canonical request is : request _ method + ' \n ' + cano...
signed_headers = self . signed_headers header_lines = "" . join ( [ "%s:%s\n" % item for item in iteritems ( signed_headers ) ] ) header_keys = ";" . join ( [ key for key in iterkeys ( self . signed_headers ) ] ) return ( self . request_method + "\n" + self . canonical_uri_path + "\n" + self . canonical_query_string + ...
def compile_geo ( d ) : """Compile top - level Geography dictionary . : param d : : return :"""
logger_excel . info ( "enter compile_geo" ) d2 = OrderedDict ( ) # get max number of sites , or number of coordinate points given . num_loc = _get_num_locations ( d ) # if there ' s one more than one location put it in a collection if num_loc > 1 : d2 [ "type" ] = "FeatureCollection" features = [ ] for idx ...
def serialize ( self , now = None ) : """Serialize this amdSec and all children to lxml Element and return it . : param str now : Default value for CREATED in children if none set : return : amdSec Element with all children"""
if self . _tree is not None : return self . _tree el = etree . Element ( utils . lxmlns ( "mets" ) + self . tag , ID = self . id_string ) self . subsections . sort ( ) for child in self . subsections : el . append ( child . serialize ( now ) ) return el
def rlmb_base_stochastic_discrete ( ) : """Base setting with stochastic discrete model ."""
hparams = rlmb_base ( ) hparams . learning_rate_bump = 1.0 hparams . grayscale = False hparams . generative_model = "next_frame_basic_stochastic_discrete" hparams . generative_model_params = "next_frame_basic_stochastic_discrete" # The parameters below are the same as base , but repeated for easier reading . hparams . ...
def yesno ( self , s , yesno_callback , casual = False ) : """Ask a question and prepare to receive a yes - or - no answer ."""
self . write ( s ) self . yesno_callback = yesno_callback self . yesno_casual = casual
def descr_prototype ( self , buf ) : """Describe the prototype ( " head " ) of the function ."""
state = "define" if self . blocks else "declare" ret = self . return_value args = ", " . join ( str ( a ) for a in self . args ) name = self . get_reference ( ) attrs = self . attributes if any ( self . args ) : vararg = ', ...' if self . ftype . var_arg else '' else : vararg = '...' if self . ftype . var_arg e...
def execute ( self , query_string , params = None ) : """Executes a query . Returns the resulting cursor . : query _ string : the parameterized query string : params : can be either a tuple or a dictionary , and must match the parameterization style of the query : return : a cursor object"""
cr = self . connection . cursor ( ) logger . info ( "SQL: %s (%s)" , query_string , params ) self . last_query = ( query_string , params ) t0 = time . time ( ) cr . execute ( query_string , params or self . core . empty_params ) ms = ( time . time ( ) - t0 ) * 1000 logger . info ( "RUNTIME: %.2f ms" , ms ) self . _upda...
def _log ( self , message ) : """Log a debug message prefixed with order book name . : param message : Debug message . : type message : str | unicode"""
self . _logger . debug ( "{}: {}" . format ( self . name , message ) )
def getAllNodeUids ( self ) : '''getAllNodeUids - Returns all the unique internal IDs from getAllChildNodeUids , but also includes this tag ' s uid @ return set < uuid . UUID > A set of uuid objects'''
# Start with a set including this tag ' s uuid ret = { self . uid } ret . update ( self . getAllChildNodeUids ( ) ) return ret
def uptodate ( name , software = True , drivers = False , skip_hidden = False , skip_mandatory = False , skip_reboot = True , categories = None , severities = None , ) : '''Ensure Microsoft Updates that match the passed criteria are installed . Updates will be downloaded if needed . This state allows you to upd...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } wua = salt . utils . win_update . WindowsUpdateAgent ( ) available_updates = wua . available ( skip_hidden = skip_hidden , skip_installed = True , skip_mandatory = skip_mandatory , skip_reboot = skip_reboot , software = software , drivers = dr...
def total_clicks ( self , url ) : """Total clicks implementation for Bit . ly Args : url : the URL you want to get the total clicks count Returns : An int containing the total clicks count Raises : BadAPIResponseException : If the API Returns an error as response"""
url = self . clean_url ( url ) clicks_url = f'{self.api_url}v3/link/clicks' params = { 'link' : url , 'access_token' : self . api_key , 'format' : 'txt' } response = self . _get ( clicks_url , params = params ) if not response . ok : raise BadAPIResponseException ( response . content ) try : total_clicks = int ...
def parse_dm_header ( f , outdata = None ) : """This is the start of the DM file . We check for some magic values and then treat the next entry as a tag _ root If outdata is supplied , we write instead of read using the dictionary outdata as a source Hopefully parse _ dm _ header ( newf , outdata = parse _ dm...
# filesize is sizeondisk - 16 . But we have 8 bytes of zero at the end of # the file . if outdata is not None : # this means we ' re WRITING to the file if verbose : print ( "write_dm_header start" , f . tell ( ) ) ver , file_size , endianness = 3 , - 1 , 1 put_into_file ( f , "> l l l" , ver , file...
def get_event_description ( event_type , event_code ) : """Retrieves the human - readable description of an LRR event . : param event _ type : Base LRR event type . Use LRR _ EVENT _ TYPE . * : type event _ type : int : param event _ code : LRR event code : type event _ code : int : returns : string"""
description = 'Unknown' lookup_map = LRR_TYPE_MAP . get ( event_type , None ) if lookup_map is not None : description = lookup_map . get ( event_code , description ) return description
def save_book ( self , book_form , * args , ** kwargs ) : """Pass through to provider BookAdminSession . update _ book"""
# Implemented from kitosid template for - # osid . resource . BinAdminSession . update _ bin if book_form . is_for_update ( ) : return self . update_book ( book_form , * args , ** kwargs ) else : return self . create_book ( book_form , * args , ** kwargs )
def get_parameter_values ( self ) : """Return a dictionary of variables with ` type ` : class : ` CFNType ` . Returns : dict : variables that need to be submitted as CloudFormation Parameters . Will be a dictionary of < parameter name > : < parameter value > ."""
variables = self . get_variables ( ) output = { } for key , value in variables . items ( ) : try : output [ key ] = value . to_parameter_value ( ) except AttributeError : continue return output
def uptime_check_config_path ( cls , project , uptime_check_config ) : """Return a fully - qualified uptime _ check _ config string ."""
return google . api_core . path_template . expand ( "projects/{project}/uptimeCheckConfigs/{uptime_check_config}" , project = project , uptime_check_config = uptime_check_config , )
def serve ( request , server ) : """Twisted Web adapter . It has two arguments : # . ` ` request ` ` is a Twisted Web request object , # . ` ` server ` ` is a pyws server object . First one is the context of an application , function ` ` serve ` ` transforms it into a pyws request object . Then it feeds the...
request_ = Request ( '/' . join ( request . postpath ) , request . content . read ( ) if not request . method == 'GET' else '' , request . args , request . args , { } ) response = server . process_request ( request_ ) request . setHeader ( 'Content-Type' , response . content_type ) request . setResponseCode ( get_http_...
def fw_create ( self , data , fw_name = None , cache = False ) : """Top level FW create function ."""
LOG . debug ( "FW create %s" , data ) try : self . _fw_create ( fw_name , data , cache ) except Exception as exc : LOG . error ( "Exception in fw_create %s" , str ( exc ) )
def start_service ( addr , n ) : """Start a service"""
s = Service ( addr ) started = time . time ( ) for _ in range ( n ) : msg = s . socket . recv ( ) s . socket . send ( msg ) s . socket . close ( ) duration = time . time ( ) - started print ( 'Raw REP service stats:' ) util . print_stats ( n , duration ) return
def clear_components ( self ) : """Clear all of the registered components"""
ComponentRegistry . _component_overlays = { } for key in self . list_components ( ) : self . remove_component ( key )
def simple_layer_stack ( include_encdec_attention , num_layers = 6 , d_ff = 2048 , num_heads = 8 , d_kv = 128 , dropout_rate = 0.1 ) : """Create a layer stack . Args : include _ encdec _ attention : a boolean num _ layers : an integer d _ ff : an integer num _ heads : an integer d _ kv : an integer dr...
ret = [ ] for _ in xrange ( num_layers ) : ret . append ( transformer_layers . SelfAttention ( num_heads = num_heads , key_value_size = d_kv , attention_kwargs = { "dropout_rate" : dropout_rate } ) ) if include_encdec_attention : ret . append ( transformer_layers . EncDecAttention ( num_heads = num_head...
def prepare_url ( self , url , params ) : """Prepares the given HTTP URL ."""
url = to_native_string ( url ) # Don ' t do any URL preparation for non - HTTP schemes like ` mailto ` , # ` data ` etc to work around exceptions from ` url _ parse ` , which # handles RFC 3986 only . if ':' in url and not url . lower ( ) . startswith ( 'http' ) : self . url = url return # Support for unicode d...
def filter_instance ( self , inst , plist ) : """Remove properties from an instance that aren ' t in the PropertyList inst - - The pywbem . CIMInstance plist - - The property List , or None . The list items must be all lowercase ."""
if plist is not None : for pname in inst . properties . keys ( ) : if pname . lower ( ) not in plist and pname : if inst . path is not None and pname in inst . path . keybindings : continue del inst . properties [ pname ]
def GetMessages ( self , formatter_mediator , event ) : """Determines the formatted message strings for an event object . Args : formatter _ mediator ( FormatterMediator ) : mediates the interactions between formatters and other components , such as storage and Windows EventLog resources . event ( EventOb...
if self . DATA_TYPE != event . data_type : raise errors . WrongFormatter ( 'Unsupported data type: {0:s}.' . format ( event . data_type ) ) event_values = event . CopyToDict ( ) file_reference = event_values . get ( 'file_reference' , None ) if file_reference : event_values [ 'file_reference' ] = '{0:d}-{1:d}' ...
def picknthweekday ( year , month , dayofweek , hour , minute , whichweek ) : """dayofweek = = 0 means Sunday , whichweek 5 means last instance"""
first = datetime . datetime ( year , month , 1 , hour , minute ) weekdayone = first . replace ( day = ( ( dayofweek - first . isoweekday ( ) ) % 7 + 1 ) ) for n in range ( whichweek ) : dt = weekdayone + ( whichweek - n ) * ONEWEEK if dt . month == month : return dt
def furtherArgsProcessing ( args ) : """Converts args , and deals with incongruities that argparse couldn ' t handle"""
if isinstance ( args , str ) : unprocessed = args . strip ( ) . split ( ' ' ) if unprocessed [ 0 ] == 'cyther' : del unprocessed [ 0 ] args = parser . parse_args ( unprocessed ) . __dict__ elif isinstance ( args , argparse . Namespace ) : args = args . __dict__ elif isinstance ( args , dict ) : ...
def get_nodes_by_qualified_name ( self , graph , qualified_name_selector ) : """Yield all nodes in the graph that match the qualified _ name _ selector . : param str qualified _ name _ selector : The selector or node name"""
qualified_name = qualified_name_selector . split ( "." ) package_names = get_package_names ( graph ) for node , real_node in self . parsed_nodes ( graph ) : if _node_is_match ( qualified_name , package_names , real_node . fqn ) : yield node
def auth ( self , transport , account_name , password ) : """Authenticates using username and password ."""
auth_token = AuthToken ( ) auth_token . account_name = account_name attrs = { sconstant . A_BY : sconstant . V_NAME } account = SOAPpy . Types . stringType ( data = account_name , attrs = attrs ) params = { sconstant . E_ACCOUNT : account , sconstant . E_PASSWORD : password } self . log . debug ( 'Authenticating accoun...
def check_pending_labels ( ast ) : """Iteratively traverses the node looking for ID with no class set , marks them as labels , and check they ' ve been declared . This way we avoid stack overflow for high line - numbered listings ."""
result = True visited = set ( ) pending = [ ast ] while pending : node = pending . pop ( ) if node is None or node in visited : # Avoid recursive infinite - loop continue visited . add ( node ) for x in node . children : pending . append ( x ) if node . token != 'VAR' or ( node . tok...
def get_prep_value ( self , value ) : """Convert value to JSON string before save"""
try : return json . dumps ( value , cls = DjangoJSONEncoder ) except Exception as e : raise ValidationError ( str ( e ) )
def deconstruct ( name ) : '''Deconstruct a queue - name to a set of arguments'''
name = coerce_unicode ( name , _c . FSQ_CHARSET ) new_arg = sep = u'' args = [ ] # can ' t get delimiter , if string is empty if 1 > len ( name ) : raise FSQMalformedEntryError ( errno . EINVAL , u'cannot derive delimiter' u'from: {0}' . format ( name ) ) delimiter , encodeseq = delimiter_encodeseq ( name [ 0 ] , _...
def set_document_unit ( self , unit ) : """Use specified unit for width and height of generated SVG file . See ` ` SVG _ UNIT _ * ` ` enumerated values for a list of available unit values that can be used here . This function can be called at any time before generating the SVG file . However to minimize the...
cairo . cairo_svg_surface_set_document_unit ( self . _pointer , unit ) self . _check_status ( )
def get_password ( prompt = 'Password: ' , confirm = False ) : """< Purpose > Return the password entered by the user . If ' confirm ' is True , the user is asked to enter the previously entered password once again . If they match , the password is returned to the caller . < Arguments > prompt : The tex...
# Are the arguments the expected type ? # If not , raise ' securesystemslib . exceptions . FormatError ' . securesystemslib . formats . TEXT_SCHEMA . check_match ( prompt ) securesystemslib . formats . BOOLEAN_SCHEMA . check_match ( confirm ) while True : # getpass ( ) prompts the user for a password without echoing # ...
def listdir ( dir_name , get_dirs = None , get_files = None , hide_ignored = False ) : """Return list of all dirs and files inside given dir . Also can filter contents to return only dirs or files . Args : - dir _ name : Which directory we need to scan ( relative ) - get _ dirs : Return dirs list - get _ ...
if get_dirs is None and get_files is None : get_dirs = True get_files = True source_dir = os . path . join ( settings . BASE_DIR , 'app' , dir_name ) dirs = [ ] for dir_or_file_name in os . listdir ( source_dir ) : path = os . path . join ( source_dir , dir_or_file_name ) if hide_ignored and dir_or_file...
def _cmp_by_local_origin ( path1 , path2 ) : """Select locally originating path as best path . Locally originating routes are network routes , redistributed routes , or aggregated routes . For now we are going to prefer routes received through a Flexinet - Peer as locally originating route compared to routes ...
# If both paths are from same sources we cannot compare them here . if path1 . source == path2 . source : return None # Here we consider prefix from NC as locally originating static route . # Hence it is preferred . if path1 . source is None : return path1 if path2 . source is None : return path2 return Non...
def lookup_default ( self , name ) : """Looks up the default for a parameter name . This by default looks into the : attr : ` default _ map ` if available ."""
if self . default_map is not None : rv = self . default_map . get ( name ) if callable ( rv ) : rv = rv ( ) return rv
def resolve_address ( endpoint_type = PUBLIC , override = True ) : """Return unit address depending on net config . If unit is clustered with vip ( s ) and has net splits defined , return vip on correct network . If clustered with no nets defined , return primary vip . If not clustered , return unit address e...
resolved_address = None if override : resolved_address = _get_address_override ( endpoint_type ) if resolved_address : return resolved_address vips = config ( 'vip' ) if vips : vips = vips . split ( ) net_type = ADDRESS_MAP [ endpoint_type ] [ 'config' ] net_addr = config ( net_type ) net_fallback =...
def get_parent_id ( element ) : """returns the ID of the parent of the given element"""
if 'parent' in element . attrib : return element . attrib [ 'parent' ] else : return element . getparent ( ) . attrib [ add_ns ( 'id' ) ]
def frequency ( data , output = 'spectraldensity' , scaling = 'power' , sides = 'one' , taper = None , halfbandwidth = 3 , NW = None , duration = None , overlap = 0.5 , step = None , detrend = 'linear' , n_fft = None , log_trans = False , centend = 'mean' ) : """Compute the power spectral density ( PSD , output =...
if output not in ( 'spectraldensity' , 'complex' , 'csd' ) : raise TypeError ( f'output can be "spectraldensity", "complex" or "csd",' ' not "{output}"' ) if 'time' not in data . list_of_axes : raise TypeError ( '\'time\' is not in the axis ' + str ( data . list_of_axes ) ) if len ( data . list_of_axes ) != dat...
def export ( group , bucket , prefix , start , end , role , poll_period = 120 , session = None , name = "" , region = None ) : """export a given log group to s3"""
start = start and isinstance ( start , six . string_types ) and parse ( start ) or start end = ( end and isinstance ( start , six . string_types ) and parse ( end ) or end or datetime . now ( ) ) start = start . replace ( tzinfo = tzlocal ( ) ) . astimezone ( tzutc ( ) ) end = end . replace ( tzinfo = tzlocal ( ) ) . a...
def iec2bytes ( size_spec , only_positive = True ) : """Convert a size specification , optionally containing a scaling unit in IEC notation , to a number of bytes . Parameters : size _ spec ( str ) : Number , optionally followed by a unit . only _ positive ( bool ) : Allow only positive values ? Return : ...
scale = 1 try : size = int ( 0 + size_spec ) # return numeric values as - is except ( TypeError , ValueError ) : spec = size_spec . strip ( ) . lower ( ) for exp , iec_unit in enumerate ( IEC_UNITS [ 1 : ] , 1 ) : iec_unit = iec_unit . lower ( ) if spec . endswith ( iec_unit ) : ...
def move_node ( self , parent , from_index , to_index ) : """Moves given parent child to given index . : param to _ index : Index to . : type to _ index : int : param from _ index : Index from . : type from _ index : int : return : Method success . : rtype : bool"""
# TODO : Should be refactored once this ticket is fixed : # https : / / bugreports . qt - project . org / browse / PYSIDE - 78 if not from_index >= 0 or not from_index < parent . children_count ( ) or not to_index >= 0 or not to_index < parent . children_count ( ) : return False parent_index = self . get_node_index...
def get_true_sponsors ( self ) : """Get the sponsors for the scheduled activity , taking into account activity defaults and overrides ."""
sponsors = self . sponsors . all ( ) if len ( sponsors ) > 0 : return sponsors else : return self . activity . sponsors . all ( )
def format_bar ( self ) : """Builds the progress bar"""
pct = floor ( round ( self . progress / self . size , 2 ) * 100 ) pr = floor ( pct * .33 ) bar = "" . join ( [ "‒" for x in range ( pr ) ] + [ "↦" ] + [ " " for o in range ( self . _barsize - pr - 1 ) ] ) subprogress = self . format_parent_bar ( ) if self . parent_bar else "" message = "Loading{} ={}{} ({}%)" . format ...
def start ( ) : '''Start the server loop'''
from . import app root , apiopts , conf = app . get_app ( __opts__ ) if not apiopts . get ( 'disable_ssl' , False ) : if 'ssl_crt' not in apiopts or 'ssl_key' not in apiopts : logger . error ( "Not starting '%s'. Options 'ssl_crt' and " "'ssl_key' are required if SSL is not disabled." , __name__ ) r...
def GetMessages ( self , formatter_mediator , event ) : """Determines the formatted message strings for an event object . Args : formatter _ mediator ( FormatterMediator ) : mediates the interactions between formatters and other components , such as storage and Windows EventLog resources . event ( EventOb...
if self . DATA_TYPE != event . data_type : raise errors . WrongFormatter ( 'Unsupported data type: {0:s}.' . format ( event . data_type ) ) event_values = event . CopyToDict ( ) return self . _ConditionalFormatMessages ( event_values )
def prev_img ( self , loop = True ) : """Go to the previous image in the channel ."""
channel = self . get_current_channel ( ) if channel is None : self . show_error ( "Please create a channel." , raisetab = True ) return channel . prev_image ( ) return True
def avro_name ( url ) : # type : ( AnyStr ) - > AnyStr """Turn a URL into an Avro - safe name . If the URL has no fragment , return this plain URL . Extract either the last part of the URL fragment past the slash , otherwise the whole fragment ."""
frg = urllib . parse . urldefrag ( url ) [ 1 ] if frg != '' : if '/' in frg : return frg [ frg . rindex ( '/' ) + 1 : ] return frg return url
def _release_info ( ) : """Check latest fastfood release info from PyPI ."""
pypi_url = 'http://pypi.python.org/pypi/fastfood/json' headers = { 'Accept' : 'application/json' , } request = urllib . Request ( pypi_url , headers = headers ) response = urllib . urlopen ( request ) . read ( ) . decode ( 'utf_8' ) data = json . loads ( response ) return data
def read_mesh ( fname ) : """Read mesh data from file . Parameters fname : str File name to read . Format will be inferred from the filename . Currently only ' . obj ' and ' . obj . gz ' are supported . Returns vertices : array Vertices . faces : array | None Triangle face definitions . normals ...
# Check format fmt = op . splitext ( fname ) [ 1 ] . lower ( ) if fmt == '.gz' : fmt = op . splitext ( op . splitext ( fname ) [ 0 ] ) [ 1 ] . lower ( ) if fmt in ( '.obj' ) : return WavefrontReader . read ( fname ) elif not format : raise ValueError ( 'read_mesh needs could not determine format.' ) else : ...
def get_objects ( self ) : """Return a list of all content objects in this distribution . : rtype : list of : class : ` boto . cloudfront . object . Object ` : return : The content objects"""
bucket = self . _get_bucket ( ) objs = [ ] for key in bucket : objs . append ( key ) return objs
def exists ( self , file_path , check_link = False ) : """Return true if a path points to an existing file system object . Args : file _ path : The path to examine . Returns : ( bool ) True if the corresponding object exists . Raises : TypeError : if file _ path is None ."""
if check_link and self . islink ( file_path ) : return True file_path = make_string_path ( file_path ) if file_path is None : raise TypeError if not file_path : return False if file_path == self . dev_null . name : return not self . is_windows_fs try : if self . is_filepath_ending_with_separator ( f...
def toArray ( self ) : """Return an numpy . ndarray > > > m = DenseMatrix ( 2 , 2 , range ( 4 ) ) > > > m . toArray ( ) array ( [ [ 0 . , 2 . ] , [ 1 . , 3 . ] ] )"""
if self . isTransposed : return np . asfortranarray ( self . values . reshape ( ( self . numRows , self . numCols ) ) ) else : return self . values . reshape ( ( self . numRows , self . numCols ) , order = 'F' )
def from_bulk_and_miller ( cls , structure , miller_index , min_slab_size = 8.0 , min_vacuum_size = 10.0 , max_normal_search = None , center_slab = True , selective_dynamics = False , undercoord_threshold = 0.09 ) : """This method constructs the adsorbate site finder from a bulk structure and a miller index , whi...
# TODO : for some reason this works poorly with primitive cells # may want to switch the coordination algorithm eventually vnn_bulk = VoronoiNN ( tol = 0.05 ) bulk_coords = [ len ( vnn_bulk . get_nn ( structure , n ) ) for n in range ( len ( structure ) ) ] struct = structure . copy ( site_properties = { 'bulk_coordina...
def raw_snapshot_data ( self , name ) : """GET / : login / machines / : id / snapshots / : name : param name : identifier for snapshot : type name : : py : class : ` basestring ` : rtype : : py : class : ` dict ` Used internally to get a raw dict of a single machine snapshot ."""
j , _ = self . datacenter . request ( 'GET' , self . path + '/snapshots/' + str ( name ) ) return j
def canonicalize_id ( reference_id ) : """Returns the canonicalized form of the provided reference _ id . WikiLeaks provides some malformed cable identifiers . If the provided ` reference _ id ` is not valid , this method returns the valid reference identifier equivalent . If the reference identifier is valid...
rid = MALFORMED_CABLE_IDS . get ( reference_id , None ) or INVALID_CABLE_IDS . get ( reference_id , None ) if rid : reference_id = rid m = _C14N_PATTERN . match ( reference_id ) if m : origin = m . group ( 1 ) return reference_id . replace ( origin , canonicalize_origin ( origin ) ) return reference_id
def _update_data ( self , data = { } ) : '''Update the data in this object .'''
# Store the changes to prevent this update from affecting it pending_changes = self . _changes or { } try : del self . _changes except : pass # Map custom fields into our custom fields object try : custom_field_data = data . pop ( 'custom_fields' ) except KeyError : pass else : self . custom_fields ...
def build ( self , requestor_private_key = None , requestor_certificate = None , other_certificates = None ) : """Validates the request information , constructs the ASN . 1 structure and then optionally signs it . The requestor _ private _ key , requestor _ certificate and other _ certificates params are all ...
def _make_extension ( name , value ) : return { 'extn_id' : name , 'critical' : False , 'extn_value' : value } tbs_request_extensions = [ ] request_extensions = [ ] has_nonce = False for name , value in self . _tbs_request_extensions . items ( ) : if name == 'nonce' : has_nonce = True tbs_request_ex...
def set_motion_detect ( self , enable ) : """Set motion detection ."""
if enable : return api . request_motion_detection_enable ( self . sync . blink , self . network_id , self . camera_id ) return api . request_motion_detection_disable ( self . sync . blink , self . network_id , self . camera_id )
def parse_napoleon_doc ( doc , style ) : """Extract the text from the various sections of a numpy - formatted docstring . Parameters doc : Union [ str , None ] The docstring to parse . style : str ' google ' or ' numpy ' Returns OrderedDict [ str , Union [ None , str ] ] The extracted numpy - styled...
napoleon_sections = [ "Short Summary" , "Attributes" , "Methods" , "Warning" , "Note" , "Parameters" , "Other Parameters" , "Keyword Arguments" , "Returns" , "Yields" , "Raises" , "Warns" , "See Also" , "References" , "Todo" , "Example" , "Examples" ] aliases = { "Args" : "Parameters" , "Arguments" : "Parameters" , "Ke...
def sort ( args ) : """% prog sort fastafile Sort a list of sequences and output with sorted IDs , etc ."""
p = OptionParser ( sort . __doc__ ) p . add_option ( "--sizes" , default = False , action = "store_true" , help = "Sort by decreasing size [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) fastafile , = args sortedfastafile = fastafile . rsplit ( "...
def marshmallow_loader ( schema_class ) : """Marshmallow loader for JSON requests ."""
def json_loader ( ) : request_json = request . get_json ( ) context = { } pid_data = request . view_args . get ( 'pid_value' ) if pid_data : pid , _ = pid_data . data context [ 'pid' ] = pid result = schema_class ( context = context ) . load ( request_json ) if result . errors : ...
def cced ( self , user , include = None ) : """Retrieve the tickets this user is cc ' d into . : param include : list of objects to sideload . ` Side - loading API Docs < https : / / developer . zendesk . com / rest _ api / docs / core / side _ loading > ` _ _ . : param user : User object or id"""
return self . _query_zendesk ( self . endpoint . cced , 'ticket' , id = user , include = include )
def update_resource_assignments ( self , id_or_uri , resource_assignments , timeout = - 1 ) : """Modifies scope membership by adding or removing resource assignments . Args : id _ or _ uri : Can be either the resource ID or the resource URI . resource _ assignments ( dict ) : A dict object with a list of re...
uri = self . _client . build_uri ( id_or_uri ) + "/resource-assignments" headers = { 'Content-Type' : 'application/json' } return self . _client . patch_request ( uri , resource_assignments , timeout = timeout , custom_headers = headers )
def pitremove_example ( ) : """run function of TauDEM , take pitremove as an example . Compare the max , min , and average of rawdem and filled DEM . The result will be : : RawDEM : Max : 284.07 , Min : 139.11 , Mean : 203.92 FilledDEM : Max : 284.07 , Min : 139.11 , Mean : 203.93"""
dem = '../tests/data/Jamaica_dem.tif' wp = '../tests/data/tmp_results' fel = 'dem_pitremoved.tif' taudem_bin = None mpi_bin = None num_proc = 2 TauDEM . pitremove ( num_proc , dem , fel , wp , mpiexedir = mpi_bin , exedir = taudem_bin ) rawdem = RasterUtilClass . read_raster ( dem ) feldem = RasterUtilClass . read_rast...
def update ( self , ** kwargs ) : """Returns new command with replaced fields . : rtype : Command"""
kwargs . setdefault ( 'script' , self . script ) kwargs . setdefault ( 'output' , self . output ) return Command ( ** kwargs )
def update ( self , _attributes = None , ** attributes ) : """Perform an update on all the related models . : param attributes : The attributes : type attributes : dict : rtype : int"""
if _attributes is not None : attributes . update ( _attributes ) if self . _related . uses_timestamps ( ) : attributes [ self . get_related_updated_at ( ) ] = self . _related . fresh_timestamp ( ) return self . _query . update ( attributes )
def merge ( self , other , inplace = None , overwrite_vars = frozenset ( ) , compat = 'no_conflicts' , join = 'outer' ) : """Merge the arrays of two datasets into a single dataset . This method generally not allow for overriding data , with the exception of attributes , which are ignored on the second dataset ....
inplace = _check_inplace ( inplace ) variables , coord_names , dims = dataset_merge_method ( self , other , overwrite_vars = overwrite_vars , compat = compat , join = join ) return self . _replace_vars_and_dims ( variables , coord_names , dims , inplace = inplace )
def SetValue ( self , identifier , value ) : """Sets a value by identifier . Args : identifier ( str ) : case insensitive unique identifier for the value . value ( object ) : value . Raises : TypeError : if the identifier is not a string type ."""
if not isinstance ( identifier , py2to3 . STRING_TYPES ) : raise TypeError ( 'Identifier not a string type.' ) identifier = identifier . lower ( ) self . _values [ identifier ] = value
def parse_reports ( self ) : """Find RSeQC junction _ annotation reports and parse their data"""
# Set up vars self . junction_annotation_data = dict ( ) regexes = { 'total_splicing_events' : r"^Total splicing Events:\s*(\d+)$" , 'known_splicing_events' : r"^Known Splicing Events:\s*(\d+)$" , 'partial_novel_splicing_events' : r"^Partial Novel Splicing Events:\s*(\d+)$" , 'novel_splicing_events' : r"^Novel Splicin...
def featured_event_query ( self , ** kwargs ) : """Query the Yelp Featured Event API . documentation : https : / / www . yelp . com / developers / documentation / v3 / featured _ event required parameters : * one of either : * location - text specifying a location to search for * latitude and longitude"""
if not kwargs . get ( 'location' ) and ( not kwargs . get ( 'latitude' ) or not kwargs . get ( 'longitude' ) ) : raise ValueError ( 'A valid location (parameter "location") or latitude/longitude combination ' '(parameters "latitude" and "longitude") must be provided.' ) return self . _query ( FEATURED_EVENT_API_URL...
def path_locations ( home_dir ) : """Return the path locations for the environment ( where libraries are , where scripts go , etc )"""
home_dir = os . path . abspath ( home_dir ) # XXX : We ' d use distutils . sysconfig . get _ python _ inc / lib but its # prefix arg is broken : http : / / bugs . python . org / issue3386 if is_win : # Windows has lots of problems with executables with spaces in # the name ; this function will remove them ( using the ~...
def vgadata ( ) : """Get data about the graphics card ."""
if os . path . isfile ( '/sbin/lspci' ) : lspci = '/sbin/lspci' else : lspci = '/usr/bin/lspci' f = os . popen ( lspci + ' -m' ) pdata = { } for line in f . readlines ( ) : p = line . split ( "\"" ) name = p [ 1 ] . strip ( ) if ( name == "VGA compatible controller" ) : pdata [ "Graphics" ] ...
def add_gene_family_to_graph ( self , family_id ) : """Make an association between a group of genes and some grouping class . We make the assumption that the genes in the association are part of the supplied family _ id , and that the genes have already been declared as classes elsewhere . The family _ id i...
family = Family ( self . graph ) gene_family = self . globaltt [ 'gene_family' ] # make the assumption that the genes # have already been added as classes previously self . model . addIndividualToGraph ( family_id , None , gene_family ) # add each gene to the family family . addMember ( family_id , self . sub ) family ...
def clean ( self ) : """Validation function that checks the dimensions of the crop whether it fits into the original and the format ."""
data = self . cleaned_data photo = data [ 'photo' ] if ( ( data [ 'crop_left' ] > photo . width ) or ( data [ 'crop_top' ] > photo . height ) or ( ( data [ 'crop_left' ] + data [ 'crop_width' ] ) > photo . width ) or ( ( data [ 'crop_top' ] + data [ 'crop_height' ] ) > photo . height ) ) : # raise forms . ValidationErr...
def select ( sel , truecase , falsecase ) : """Multiplexer returning falsecase for select = = 0 , otherwise truecase . : param WireVector sel : used as the select input to the multiplexer : param WireVector falsecase : the WireVector selected if select = = 0 : param WireVector truecase : the WireVector select...
sel , f , t = ( as_wires ( w ) for w in ( sel , falsecase , truecase ) ) f , t = match_bitwidth ( f , t ) outwire = WireVector ( bitwidth = len ( f ) ) net = LogicNet ( op = 'x' , op_param = None , args = ( sel , f , t ) , dests = ( outwire , ) ) working_block ( ) . add_net ( net ) # this includes sanity check on the m...
def order_snapshot_space ( self , volume_id , capacity , tier , upgrade , ** kwargs ) : """Orders snapshot space for the given file volume . : param integer volume _ id : The ID of the volume : param integer capacity : The capacity to order , in GB : param float tier : The tier level of the file volume , in I...
file_mask = 'id,billingItem[location,hourlyFlag],' 'storageType[keyName],storageTierLevel,provisionedIops,' 'staasVersion,hasEncryptionAtRest' file_volume = self . get_file_volume_details ( volume_id , mask = file_mask , ** kwargs ) order = storage_utils . prepare_snapshot_order_object ( self , file_volume , capacity ,...
def logpdf ( self , mu ) : """Log PDF for Skew t prior Parameters mu : float Latent variable for which the prior is being formed over Returns - log ( p ( mu ) )"""
if self . transform is not None : mu = self . transform ( mu ) return self . logpdf_internal_prior ( mu , df = self . df0 , loc = self . loc0 , scale = self . scale0 , gamma = self . gamma0 )
def unique_value_groups ( ar , sort = True ) : """Group an array by its unique values . Parameters ar : array - like Input array . This will be flattened if it is not already 1 - D . sort : boolean , optional Whether or not to sort unique values . Returns values : np . ndarray Sorted , unique values...
inverse , values = pd . factorize ( ar , sort = sort ) groups = [ [ ] for _ in range ( len ( values ) ) ] for n , g in enumerate ( inverse ) : if g >= 0 : # pandas uses - 1 to mark NaN , but doesn ' t include them in values groups [ g ] . append ( n ) return values , groups
def get_info ( self ) : """Parses the output of a " show info " HAProxy command and returns a simple dictionary of the results ."""
info_response = self . send_command ( "show info" ) if not info_response : return { } def convert_camel_case ( string ) : return all_cap_re . sub ( r'\1_\2' , first_cap_re . sub ( r'\1_\2' , string ) ) . lower ( ) return dict ( ( convert_camel_case ( label ) , value ) for label , value in [ line . split ( ": " ...
def authorgroup ( self ) : """A list of namedtuples representing the article ' s authors organized by affiliation , in the form ( affiliation _ id , dptid , organization , city , postalcode , addresspart , country , auid , indexed _ name , surname , given _ name ) . If " given _ name " is not present , fall...
out = [ ] fields = 'affiliation_id dptid organization city postalcode ' 'addresspart country auid indexed_name surname given_name' auth = namedtuple ( 'Author' , fields ) items = listify ( self . _head . get ( 'author-group' , [ ] ) ) for item in items : # Affiliation information aff = item . get ( 'affiliation' , ...
def display ( self , xaxis , alpha , new = True ) : """E . display ( xaxis , alpha = . 8) : Arguments : xaxis , alpha Plots the CI region on the current figure , with respect to xaxis , at opacity alpha . : Note : The fill color of the envelope will be self . mass on the grayscale ."""
if new : figure ( ) if self . ndim == 1 : if self . mass > 0. : x = concatenate ( ( xaxis , xaxis [ : : - 1 ] ) ) y = concatenate ( ( self . lo , self . hi [ : : - 1 ] ) ) fill ( x , y , facecolor = '%f' % self . mass , alpha = alpha , label = ( 'centered CI ' + str ( self . mass ) ) ) ...
def in_miso_and_inner ( self ) : """Test if a node is miso : multiple input and single output"""
return len ( self . successor ) == 1 and self . successor [ 0 ] is not None and not self . successor [ 0 ] . in_or_out and len ( self . precedence ) > 1 and self . precedence [ 0 ] is not None and not self . successor [ 0 ] . in_or_out
def rejected ( reason ) : """Creates a promise object rejected with a certain value ."""
p = Promise ( ) p . _state = 'rejected' p . reason = reason return p